Home » Java programming language

Java Thread Class Thread.State getState() method with Example

Java Thread Class Thread.State getState() method: Here, we are going to learn about the Thread.State getState() method of Thread class with its syntax and example.
Submitted by Preeti Jain, on July 21, 2019

Thread Class Thread.State getState()

  • This method is available in package java.lang.Thread.getState().
  • This method is used to return the state of this thread.
  • When we execute a thread so there are various states for normal execution of the thread [States of the Thread like, start, ready, running, waiting, blocked, terminate].
  • This method is not final so we can override this method in child class.
  • The return type of this method is Thread.State so it returns the state of this thread
  • This method does not raise any exception.

Syntax:

    Thread.State getState(){
    }

Parameter(s):

We don't pass any object as a parameter in the method of the Thread.

Return value:

The return type of this method is Thread.State, it returns the state of this thread.

Java program to demonstrate example of getState() method

/*  We will use Thread class methods so we are importing 
    the package but it is not mandate because 
    it is imported by default
*/

import java.lang.Thread;

class GetThreadState extends Thread {
    // Override run() of Thread class
    public void run() {
        // By using getState() method is used to return 
        // the state of this thread
        System.out.println("The state of this thread is : " + Thread.currentThread().getState());

        /* This is another way of writing the above statement
        Thread.State th_state = Thread.currentThread().getState();
        System.out.println("The state of this thread is : "+th_state);*/
    }

    public static void main(String[] args) {
        // Creating an object of GetThreadState class
        GetThreadState gt_state = new GetThreadState();

        // We are setting the name of the thread GetThreadState
        gt_state.setName("GetThreadState");

        // Calling start() method with GetThreadState class 
        // object of Thread class/
        gt_state.start();

        // By using getName() method to return the name of this 
        // thread [GetThreadState]
        System.out.println("The name of this thread is " + " " + gt_state.getName());
    }
}

Output

E:\Programs>javac GetThreadState.java

E:\Programs>java GetThreadState
The name of this thread is  GetThreadState
The state of this thread is : RUNNABLE


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.