Java Thread get thread's state

Introduction

A thread can be in a number of different states.

To get the current state of a thread, call the getState() method defined by Thread.

Thread.State getState() 

It returns a value of type Thread.State.

Value State
BLOCKED thread has suspended execution because it is waiting to acquire a lock.
NEW thread has not begun execution.
RUNNABLEthread is currently executing or will execute when it gains access to the CPU.
TERMINATEDAthread has completed execution.
TIMED_WAITING thread has suspended execution for a specified period of time
WAITING thread has suspended execution
class MyThread implements Runnable {
  private String name; // name of thread
  private Thread t;
  
  public MyThread(String threadname) {
    name = threadname;//from w w  w  .ja  va  2  s  . co  m
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    t.start(); // Start the thread
  }
  public void run() {
    System.out.println(name + " is running.");
  }
  public Thread getThread() {
    return t;
  }

}

public class Main {
  public static void main(String args[]) {
    MyThread ob1 = new MyThread("One");
    MyThread ob2 = new MyThread("Two");

    try {
      System.out.println(ob1.getThread().getState());
      System.out.println(ob2.getThread().getState());
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }

    // wait for threads to finish
    try {
      System.out.println("Waiting for threads to finish.");
      ob1.getThread().join();
      ob2.getThread().join();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }
 
    System.out.println("Main thread exiting.");
  }
}



PreviousNext

Related