Monitor a thread's status. : Wait Notify « Thread « Java Tutorial






class MyThread extends Thread{
  boolean waiting= true;
  boolean ready= false;

  public void run() {
    String thrdName = Thread.currentThread().getName();
    System.out.println(thrdName + " starting.");
    while(waiting) 
      System.out.println("waiting:"+waiting); 
    System.out.println("waiting...");
    startWait(); 
    try {
      Thread.sleep(10000);
    } catch(Exception exc) {
      System.out.println(thrdName + " interrupted.");
    }
    System.out.println(thrdName + " terminating.");
  }

  synchronized void startWait() {
    try {
      while(!ready){ 
        wait();
      }
    } catch(InterruptedException exc) {
      System.out.println("wait() interrupted");
    }
  }

  synchronized void startWork() {
    ready = true;
    notify();
  }
}

public class Main {
  public static void main(String args[]) throws Exception{
      MyThread thrd = new MyThread();
      thrd.setName("MyThread #1");
      System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );

      thrd.start();
      Thread.sleep(50);
      System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );

      thrd.waiting = false;
      Thread.sleep(50); 
      System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );

      thrd.startWork();
      Thread.sleep(50);
      System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );

      if(thrd.isAlive()) 
        System.out.println("alive");
      System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );
  }

}








10.21.Wait Notify
10.21.1.Use wait() and notify() from Object class
10.21.2.Monitor a thread's status.
10.21.3.Stopping a Thread: set a boolean variable that the thread checks occasionally
10.21.4.Pausing a Thread: set boolean a variable that the thread checks occasionally