Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

How to get the state of a thread in Java

Ravi

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:

  1. New
  2. Runnable
  3. Running
  4. Non-Runnable (Blocked)
  5. 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:

  1. NEW: The thread has not yet started execution.
  2. RUNNABLE: A thread in execution.
  3. BLOCKED: A thread in a blocked state.
  4. WAITING: A thread in a waiting state.
  5. TIMED_WAITING: A state for a waiting thread with a specified waiting time.
  6. 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());
    }
}
Using the getState() method

Explanation

  • Lines 4 to 7: We create a thread called threadObject that 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 on threadObject.
  • Line 11: We invoke the join() method on threadObject.
  • Line 12: We print the state of the threadObject.

RELATED TAGS

java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring