Java Threads

A thread is the course or path followed while a program is being run. The main thread, which is typically present in all programs, is provided by the JVM, or Java Virtual Machine, at the beginning of the program's execution. In this article, we will talk more about the threads in Java, the creation of a thread in Java, and ways to monitor a thread along with the life cycle of a java thread. We will also talk about various states that a thread goes in during the whole process.

Thread in Java

A program can perform several tasks at once more effectively by using threads. Complex tasks can be carried out in the background using threads without interfering with the main program. Implementing an interface and extending a class are the two steps required to create a thread in Java. Java's java.lang library creates and manages every thread. thread type.

A single-threaded Java application can only handle one task at a time and contains just one Java thread. Multi-threading is the process of handling many tasks concurrently by creating numerous Java threads, each of which handles a different task.

There is a class called "thread" that offers constructors and methods for creating and managing threads. Extending the Object class, the Thread class implements the Runnable interface. The majority of commercial Java applications heavily rely on multithreading. The following instances of multi-threads will demonstrate why this is done for various reasons:

  • For quicker background/batch task processing: Multi-threading enables the simultaneous execution of numerous processes by allowing each task to run independently. As a result, the total processing time is decreased.
  • To benefit from contemporary CPUs, most systems today include several processors, each of which has numerous cores. By allowing distinct threads to be executed by various processors, multi-threading makes it possible to use the system resources more effectively.
  • Users anticipate quick response times from Java apps. Response time can be slashed by splitting up the processing required for a request into smaller pieces and having various threads do the work in parallel.
  • To simultaneously serve several users: Many users can be supported concurrently by Java application servers like Tomcat, JBoss, Oracle WebLogic, and IBM WebSphere. Only by using many threads can this be accomplished. The application server creates one Java thread to process each request.

Why should I monitor the thread in java?

The JMX interfaces offered by contemporary JVMs enable monitoring tools to keep track of thread activity within the JVM. We should monitor threads in Java for the following purposes:

  • To know the number of threads currently running in the JVM
  • To know the number of threads present in each state: runnable, running, time waiting, blocked, timed waiting, etc.
  • To understand the line of code is each thread executing and what is the stack trace.
  • To know if there is any thread taking up excessive CPU resources and if so, what code block is being executed
  • To calculate the growth of threads in JVM at a particular time
  • To know the configuration of thread pools in the application server and what are the max limits
  • To determine the utilization of each thread pool if any pool’s current usage close to its maximum

Wish to make a career in the world of Java? Start with HKR'S Java Training!

Java Certification Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Creating a thread in Java

Implementing the runnable interface and overriding the run() method allows you to create threads. The start() method can then be called after creating a thread object.

There are 2 major ways of creating a thread:

  1. By Implementing the java.lang.Runnable interface
  2. By extending the java.lang.Thread class

Thread Class

Constructors and methods for starting and managing threads are available in the Thread class. The thread implements the Runnable interface and extends the Object.

Runnable Interface

The Runnable interface should be implemented by any classes that have instances that are meant to be executed by threads. The run() method is the only one available for the Runnable interface.

Let us see the benefits of creating threads below:

  • Java Threads are more lightweight when compared to processes; creating a thread requires less time and resources.
  • Data and code from a thread's parent process are shared.
  • Process communication is more complicated than thread communication.
  • Changing between processes is typically more expensive than changing between threads.

The usual error is to use the run() method to start a thread instead of the start() method.

Method 1: Creating a thread using Thread Class

import java.io.*;

class ABC extends Thread {

public void run()

{

System.out.print("Welcome to HKR Training");

}

public static void main(String[] args)

{

ABC x = new ABC();

x.start();

}

}

The output of the Java code is:

Welcome to HKR Training

Method 2: By implementing a runnable Interface

import java.io.*;

class ABC implements Runnable {

public static void main(String args[])

{

ABC abc = new ABC();


        Thread x = new Thread(abc, "Welcome");


x.start();


System.out.println(x.getName());

}

@Override public void run()

{

System.out.println("Inside run method");

}

}

The output of the Java code is:

Welcome

Inside run method

The life cycle of thread in Java

A thread can be in any of the following states in Java during its complete life cycle. These are the states:

1. New: A new thread is always in the new state when it is created. The function hasn't been run yet, thus it hasn't started to execute for a thread in the new state.

2. Active: A thread switches from the new state to the active state when it uses the start() method. The runnable state and the running state are both contained within the active state.

  • Runnable: When a thread is prepared to execute, it is then transferred to the runnable state. The thread may be running or prepared to run at any given moment while it is in a runnable state. The thread scheduler's responsibility is to provide the thread enough time to run, i.e., to move the thread into the running state.
  • Running: The thread transitions from the runnable state to the running state when it receives the CPU. The most frequent transitions in a thread's state are from runnable to running and back to runnable.

3. Waiting State: A thread is either in the blocked state or the waiting state whenever it is dormant for a while (but not forever). The task of the thread scheduler is to choose which threads to accept and which ones to refuse when there are many threads in the waiting or blocked state. The chosen thread is then given the chance to run.

4. Timed Waiting: Starvation can result from waiting. For instance, a thread (whose name is A) has entered a code's vital area and is unable to leave it. In this case, another thread (whose name is B) is forced to wait interminably, which causes it to starve. A timed waiting state is provided to thread B in order to prevent this occurrence. Therefore, the thread is only in the waiting state for a certain amount of time and not always. When we use the sleep() method on a particular thread, we are actually engaging in timed waiting. The thread enters the timed wait state using the sleep() function. The thread awakens when the allotted time has passed and resumes execution where it left off.

5. Terminated: A thread can enter the termination state for the reasons listed below:

  • A thread exists or terminates normally once it has completed its task.
  • A segmentation fault or unhandled exception are examples of uncommon events that can cause an abnormal termination.

A thread that has been terminated means it is no longer active in the system. In other words, the thread is inactive and cannot be revived (made active again after being killed).

The image below illustrates the states in the lifecycle of a thread:

Life Cycle Of a thread

Want to know more about Java, visit here Java Tutorial!

Subscribe to our youtube channel to get new updates..!

Constructors of Java Threads

Using the Thread Class, which extends a Thread class that can implement the Runnable Interface and offers constructors to create as well as perform actions on a Thread, we can run threads in Java. We create the Thread using the following constructors:

1. Thread(): Let us see the Java code below to illustrate thread() in Java

import java.io.*;

import java.util.*;

public class HKR extends Thread {

public void run()

{

System.out.println("The thread has started running");

}

public static void main(String[] args)

{

HKR x = new HKR();

x.run();

}

}

The output of this java code is:

The thread has started running

2. Thread(Runnable r,):  Let us see the Java code below to understand illustration in Java

import java.io.*;

import java.util.*;


public class HKR implements Runnable {

public void run()

{

System.out.println(

"The thread is successfully running");

}

public static void main(String[] args)

{

HKR x = new HKR();

Thread T= new Thread(x);

T.run();

}

}

The output of this java code is:

The thread is successfully running

3. Thread(String name): Let us see the Java code below to understand the illustration in Java


import java.io.*;

import java.util.*;


public class HKR {

public static void main(String args[])

{

Thread T = new Thread("Hello Learners. Welcome to HKR!");

T.start();


String str = T.getName();

System.out.println(str);

}

}

The output of this java code is:

Hello Learners. Welcome to HKR!

4. Thread(String name, runnable r): Let us see the Java code below to understand the illustration in Java

import java.io.*;

import java.util.*;

public class HKR implements Runnable {

public void run()

{

System.out.println(

"The thread is ready and successfully running");

}

public static void main(String[] args)

{

Runnable x = new HKR();

Thread T = new Thread(x, "Thread");

T.run();

String s = T.getName();

System.out.println(s);

}

}

The output of this java code is:

The thread is ready and successfully running

Thread

Top 30 frequently asked JAVA Interview Questions!

Java Certification Training

Weekday / Weekend Batches

 Conclusion

In this article, we have talked about Java threads along with the creation of a thread in Java, and ways to monitor a thread along with the life cycle of a java thread. A program can perform several tasks at once more effectively by using threads. A thread is a course or path followed while running a program. The main thread, which is typically present in all programs, is provided by the JVM. We have also talked about various states that a thread goes in during the whole process such as new, runnable, terminated, etc

Related articles:

Find our upcoming Java Certification Training Online Classes

  • Batch starts on 6th Dec 2022, Weekday batch

  • Batch starts on 10th Dec 2022, Weekend batch

  • Batch starts on 14th Dec 2022, Weekday batch

Global Promotional Image
 

Categories

Request for more information

Amani
Amani
Research Analyst
As a content writer at HKR trainings, I deliver content on various technologies. I hold my graduation degree in Information technology. I am passionate about helping people understand technology-related content through my easily digestible content. My writings include Data Science, Machine Learning, Artificial Intelligence, Python, Salesforce, Servicenow and etc.

Yes, Java is multi-threaded by nature. Numerous distinct threads may run concurrently and independently in a single Java program.

The start() function on the new Thread object must be called before the thread can begin to run after being formed by instantiating a Thread object or an object that extends Thread.

 In Java, threads are used for everything that runs. Even if you don't explicitly call it, every program in the JVM world has at least one thread.

A program can perform numerous tasks at once more effectively because of threads.

A single-threaded Java application can only handle one task at a time and contains just one Java thread. Multi-threading is the process of handling many tasks concurrently by creating numerous Java threads, each of which handles a different task.