Java - Get the current thread state

Introduction

getState() method of the Thread class returns the state of a thread at any time.

This method returns one of the constants of the Thread.State enum type.

The following code demonstrate the transition of a thread from one state to another.

Demo

class ThreadState extends Thread {
  private boolean keepRunning = true;
  private boolean wait = false;
  private Object syncObject = null;

  public ThreadState(Object syncObject) {
    this.syncObject = syncObject;
  }/*from  www .  j a  v  a2 s.c  om*/

  public void run() {
    while (keepRunning) {
      synchronized (syncObject) {
        if (wait) {
          try {
            syncObject.wait();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
      }
    }
  }

  public void setKeepRunning(boolean keepRunning) {
    this.keepRunning = keepRunning;
  }

  public void setWait(boolean wait) {
    this.wait = wait;
  }
}

public class Main {
  public static void main(String[] args) {
    Object syncObject = new Object();
    ThreadState ts = new ThreadState(syncObject);
    System.out.println("Before start()-ts.isAlive():" + ts.isAlive());
    System.out.println("#1:" + ts.getState());

    ts.start();
    System.out.println("After start()-ts.isAlive():" + ts.isAlive());
    System.out.println("#2:" + ts.getState());
    ts.setWait(true);

    sleep(100);

    synchronized (syncObject) {
      System.out.println("#3:" + ts.getState());
      ts.setWait(false);
      syncObject.notifyAll();
    }
    sleep(2000);
    System.out.println("#4:" + ts.getState());
    ts.setKeepRunning(false);

    sleep(2000);
    System.out.println("#5:" + ts.getState());
    System.out.println("At the end. ts.isAlive():" + ts.isAlive());
  }

  public static void sleep(long millis) {
    try {
      Thread.currentThread().sleep(millis);
    } catch (InterruptedException e) {
    }
  }
}

Result

Related Topic