How to get the state of a thread in Java
Overview
In this shot, we’ll learn to retrieve the thread state.
A thread lifecycle defines the different states of the thread. A thread can be in five major states:
- New
- Runnable
- Running
- Non-Runnable (Blocked)
- Terminated
Note: Refer How to use threads in Java to learn more about the thread lifecycle.
getState() method
The getState() method of the Thread class is an instance method that returns the state of the thread object on which this method is invoked.
Syntax
The syntax of the method is as follows:
public State getState()
Parameters
The method has no parameters.
Return value
This method returns an enum State that has the following values:
NEW: The thread has not yet started execution.RUNNABLE: A thread in execution.BLOCKED: A thread in a blocked state.WAITING: A thread in a waiting state.TIMED_WAITING: A state for a waiting thread with a specified waiting time.TERMINATED: The thread is terminated.
Code
Let’s look at the code below:
public class Main {public static void main(String[] args) throws InterruptedException {Thread threadObject = new Thread(() -> {System.out.println("Thread in execution");System.out.println("Current state of the thread - " + Thread.currentThread().getState());});System.out.println("State of the thread - " + threadObject.getState());threadObject.start();threadObject.join();System.out.println("State of the thread - " + threadObject.getState());}}
Explanation
- Lines 4 to 7: We create a thread called
threadObjectthat prints a string and its current state. - Line 9: We print the state of the
threadObject. - Line 10: We start the thread’s execution by invoking the
start()method onthreadObject. - Line 11: We invoke the
join()method onthreadObject. - Line 12: We print the state of the
threadObject.