Java Thread getState() Method



Description

The Java Thread getState() method returns the state of this thread. It is designed for use in monitoring of the system state, not for synchronization control.

Declaration

Following is the declaration for java.lang.Thread.getState() method

public Thread.State getState()

Parameters

NA

Return Value

This method returns this thread's state.

Exception

NA

Example: Getting state of the thread created using Runnable Interface

The following example shows the usage of Java Thread getState() method. In this program, we've created a thread class ThreadDemo by implementing Runnable interface. In run() method, state of current thread is printed using getState() method. In main method, we've created the ThreadDemo thread and using start() method, this thread is started.

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   public void run() {

      // returns the state of this thread
      Thread.State state = Thread.currentThread().getState();
      System.out.println(Thread.currentThread().getName());
      System.out.println("state = " + state);
   }

   public static void main(String args[]) {
      Thread t = new Thread(new ThreadDemo());
      
      // this will call run() function
      t.start();   
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

Thread-0
state = RUNNABLE

Example: Getting state of the thread created using Thread Class

The following example shows the usage of Java Thread getState() method. In this program, we've created a thread class ThreadDemo by extending Thread class. In run() method, state of current thread is printed using getState() method. In main method, we've created the ThreadDemo thread and using start() method, this thread is started.

package com.tutorialspoint;

public class ThreadDemo extends Thread {

   public void run() {

      // returns the state of this thread
      Thread.State state = Thread.currentThread().getState();
      System.out.println(Thread.currentThread().getName());
      System.out.println("state = " + state);
   }

   public static void main(String args[]) {
      Thread t = new Thread(new ThreadDemo());
      
      // this will call run() function
      t.start();   
   }
} 

Output

Let us compile and run the above program, this will produce the following result −

Thread-1
state = RUNNABLE
java_lang_thread.htm
Advertisements