×

Java Thread Lifecycle: States and Stages

Multithreading

Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process consists of many small jobs. Each task has a "thread" designation or representation. Threads are therefore fast processes. The term "multithreading" refers to having many threads working simultaneously within a process.

What does Java Multithreading Mean?

Multithreading in Java is defined as the concurrent execution of multiple threads. It is a simultaneous procedure in which the process of execution is done continuously. Multithreading ensures the optimum usage of processing units.

Thread

Since we were discussing a lot about threads, what exactly do we mean by Java threads?

Threads are defined as sub-processes that are very lightweight. All threads are non-dependent and unique to each other. They all have different paths of execution and are small units in operating systems.

To carry out complicated processes in the background, we made use of Java's thread idea. All duties are carried out without having an impact on the primary programming.

Another perk of employing threads is that if one thread encounters an error or exception while running, it does not interfere with the operation of any other threads. Within the process, a thread runs, and there can be more than one thread per process. The threads change between various contexts. The operating system may include many processes.

Multitasking

This multithreading, along with multiprocessing, is used to achieve complete multitasking. To use the CPU, we prefer multitasking, and in this process, many numbers of tasks are executed concurrently. To achieve this task, both multiprocessing and multithreading are taken into consideration. When compared with multiprocessing, multithreading is preferred because of its context switching between the parts of the programs, and the main important use of this multithreading is memory usage. The smaller parts of programs will use the same memory area, allowing multiple threads to share a memory, and this will help to save and control the memory. Through this multithreading, we can save memory and the processing time is also less.

Lifecycle of a Thread

Since a thread is a sub-process, it will be in different states of execution, and those states are called thread states. A thread is only ever in one of the states depicted. The existing thread states are

  1. New state
  2. ready or active state
  3. Waiting or Blocked state
  4. Timed Waiting state
  5. Terminated state

Thread Execution States Explanation

1. New state

It is the birth state of a thread, which means a fresh thread is created. The new thread should always be in the new state. When a thread is in a new state, it states that the execution has not started yet and that the code has not started. To begin the execution, we must call the start() method.

2. Ready or Active State

This state is also defined as the "ready phase" or "queue". The thread achieves a runnable state whenever the start() method is used. Which threads run for how long is determined by the thread scheduler. When the start() method is called although the state is in this, the execution begins. And from the new to the ready level, the thread will transform. This stage is further broken down into the two categories of runnable states and running states.

Runnable State

When the execution is started, the thread that is ready to run will enter into the runnable state. In this state, the thread might be active or prepared to start at any given moment. The Scheduler will take the responsibility of moving the executing thread to the running state.

The runnable state is occupied by threads that are ready to be executed and are awaiting their turn. The threads are usually stored in a queue while they are in a runnable state. This happens in cases where a program that executes all the threads provides a set amount of time to each thread for the execution process. Every thread in the runnable state runs for a very small unit of time.

Running State

This state is a part of the thread active state. In the running state, all the runnable threads are now moved to the running state where all the threads reach the CPU. The most common thread state transition is from a runnable state to a running state and back to a runnable state as usual.

3. Waiting or Blocked State

This stage is also called as inactive state because the thread may be inactive or will not run for a specific small span of time. By the way the thread will not be permanently in inactive state. This means that the thread may be waiting for the execution, or the thread may be in the blocked state.

This can be explained with an example

If there are two threads t1 and t2. Both the threads want to use a machine, and only one thread can perform any operation on the machine. Let’s say t1 is executing in the machine, then t2 will be in the blocked or waiting state such that t1 can complete its task without any interruptions. While t2 that is in the waiting state cannot done any executions while in the waiting state and will not consume or interfere with the processing cycle of central processing unit.

Thread t2 will come to the active state when the thread scheduler reactive thread t2 after completion of tasks by t1. In any execution the thread scheduler plays the most important role. The main role of the thread scheduler is to choose or deny the threads to run which are in the waiting state or blocked state.

The parent thread, which indicates that the thread is stuck or waiting, calls the join() method. As a result, the tasks can be finished first by the child threads. When every one of the child threads successfully finished their work, a notification is transmitted to the primary thread, which therefore enters the active state as well as begins execution.

4. Timed Waiting State

The thread is permitted to sleep for a set amount of time in this state. Therefore, if there are two threads, first and second, the second thread must wait a very long time to execute if the first thread is in an abnormal condition and unable to do so. When this occurs, the thread will use the sleep () method to enter a timed waiting state for a predetermined amount of time. When the time is up, the thread will awaken and resume execution from where it left off.

5. Terminated State

This state is also called as dead state which means that the thread is dead and not present in the system at all. We cannot retrieve the thread for execution once the thread is killed.

Terminated thread means it is either completed its task to the fullest or the thread that cannot be able to perform has left the execution. When the thread completes its task, it exits normally whereas when there are few abnormal cases like exceptions or segmentation errors, the thread will terminate abnormally called abnormal termination.

Java Thread Lifecycle: States and Stages

Thread Implementation

While implementing thread program if we want to find out which state thread lies in, we must use Thread. getState () method so that the thread existing state will be returned.

Few of the thread summary of Enum constants are defined below

  1. public static final Thread. State NEW
  2. public static final Thread. State RUNNABLE
  3. public static final Thread. State RUNNABLE
  4. public static final Thread. State WAITING
  5. public static final Thread. State TIMED_WAITING
  6. public static final Thread. State TERMINATED

All the above-mentioned declarations define the state of a thread at various stages like new state, runnable state, waiting & time waiting and also terminated states in multithreading.

Example Java program for implementation of different states and lifecycle of the thread

Code

// Example Java program to implement thread lifecycle and states
import java.io.*;
import java.lang.*;
class thread implements Runnable {
public void run ()
{
// this try block will move thread 2 to timed waiting state
try
{
Thread.sleep(100);
}
//to handle if there is any exception
catch(Interrupted Exception e)
{
System.out.print(e);
}
 
// join() method is invoked on thread 2, the current state of thread 1 is printed 
System.out.print(Demo.thread1.getState());


try
{
Thread.sleep(2000);
}
// to handle the exception
catch(Interrupted Exception e)
{
System.out.print(e);
}
}
}


// implementing base class Demo
public class Demo implements Runnable
{
// declare first thread
public static Thread thread1; 
// declare obj
public static Demo obj;          
 // main function
public static void main(String[] args)
{
obj = new Demo();
thread1 = new Thread(obj);


// thread 1 is initialized that means it is in the NEW state
// display thread 1 current state 
System.out.print (thread1.getState());


thread1.start();


// now thread 1 is in runnable state after invoking start () method
// display the state of thread 1 after invoking start () method


System.out.print(thread1.getState());
}
public void run()
{
thread t = new thread();
Thread thread2 = new Thread(t);


// thread 2 is initialized that means it is in the NEW state
// display thread 2 current state


System.out.print(thread2.getState());
thread2.start();


// now thread 1 is in runnable state after invoking start () method
// display the state of thread 1 after invoking start () method


System.out.print(thread2.getState());


// to move thread 1 to timed waiting state
try
{
Thread.sleep(300);
}
// to handle interrupted exceptions
catch(Interrupted Exception e)
{
System.out.print(e);
}


// display the state of thread 2 after invoking sleep () method
System.out.print(thread2.getState());
Try
// join() is called to send thread 2 to dead state
{
thread2.join();
}
// to handle the exception
catch(Interrupted Exception e)
{
System.out.print(e);
}
System.out.print(thread2.getState());
}
}

Output

C:\java>javac Demo.java
C:\java>java Demo
NEW
RUNNABLE
NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TERMINATED 

Related Topics

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

How to avoid deadlock in java

Deadlock: A deadlock is an event that never going to occur. In java, deadlock is just a part of the multithreading. It is an environment that allows us to run multiple...

4 minutes read.

Scanner in Java

Static way of Programming: When a variable can’t change its value during run time is called a Static way of programming. In this programming a variable is directly assigned to a...

4 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Java Read File

Java provides its users with many ways of reading a file. To read a text file, you can use a FileReader, BufferedReader, or Scanner. Each utility offers something special for...

6 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.

Sudoku in Java

Sudoku is a combinatorial-number-placement puzzle with a logic-based approach. The goal of a traditional Sudoku puzzle is to fill in the numbers on a 9 by 9 grid so that...

6 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Accessors and Mutator in Java

Introduction Accessors and mutators are used in Java to get and set the value of private fields, respectively. Accessors and mutators are both referred to as getters and setters, respectively. The...

6 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Stable Marriage Problem in Java

Given N men and N women, the Stable Marriage Problem asks you to match up the men and women in such a way that there are never any two people...

6 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.