Articles

Explain Lifecycle of a thread in Java?

Share

Thread lifecycle in Java

A thread goes through various states after its creation.  It involves runnable, running, blocked and terminated. These are the following states:-

New

At the time, when a thread object is defined, it is said to be born and ready to execute. It begins its life from this state. A thread can be created using the Thread class and Runnable interface.

Thread thread1 = new Thread() // using Thread class

From this state, it ready to move to a runnable state by calling the start() method.

Runnable

It is the state where a thread may start executing at any point of time. Until it gets the CPU, it waits with already waiting thread queue. The thread having the highest priority would get the CPU first and if all are having the same priority, then they would run in first-in,first-out fashion.
It is also possible to invoke a particular thread among the same priorities using yield() method.

Running

It means CPU time has been allocated to the thread and it is now executing and performing its assigned task.
From this state, it can jump to suspended state, blocked state and also to the terminated state.

Blocked

A thread ends up with this state when it waits for some resources required for completing its task or for other threads to perform its job first. sleep() and wait() are some methods that put down a thread to the blocked state. It is possible that the thread can send to a runnable state again.

Suppose, it issues Input/Output request to CPU, the CPU immediately puts the thread to a blocked state until the request fulfills.

Terminated State

This is the last stage of thread lifecycle. When a thread finishes its task, it goes to the terminated state. It is also possible that a thread is forced to kill due to some error or event.

This post was last modified on June 18, 2020

Sandeep Verma

Published by
Sandeep Verma
Tags: best java books diagram java multithreading state thread Thread lifecycle in Java