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:
Note: Refer How to use threads in Java to learn more about the thread lifecycle.
getState()
methodThe getState()
method of the Thread
class is an instance method that returns the state of the thread object on which this method is invoked.
The syntax of the method is as follows:
public State getState()
The method has no parameters.
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.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());}}
threadObject
that prints a string and its current state.threadObject
.start()
method on threadObject
.join()
method on threadObject
.threadObject
.