×

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 Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are...

3 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 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.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the...

3 minutes read.

How to Create an Immutable Class in Java

How to Create an Immutable Class in Java In Java, immutable means something that cannot be change. A class is called an immutable class if its content cannot be changed, once...

3 minutes read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Java Math floorDiv() Method

The floorDiv () method of Math class returns the largest integer value that is less than or equal to the algebraic quotient. It firstly divides the dividend and divisor and...

2 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Deque in Java

Deque in java collections with Example Deque is short for “double-ended queue.” It is a linear collection that extends the Queue interface and supports insertion and deletion of the element at both the...

3 minutes read.