Monitor a thread's status. : Thread Status « Threads « Java






Monitor a thread's status.

 

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

  MyThread() {
  }
  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(1000);
    } 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 notice() {
    ready = true;
    notify();
  }
}

public class Main {
  public static void main(String args[]) throws Exception{
      MyThread thrd = new MyThread();
      thrd.setName("MyThread #1");
      showThreadStatus(thrd);

      thrd.start();
      Thread.sleep(50);
      showThreadStatus(thrd);

      thrd.waiting = false;
      Thread.sleep(50); 
      showThreadStatus(thrd);

      thrd.notice();
      Thread.sleep(50);
      showThreadStatus(thrd);
      while(thrd.isAlive()) 
        System.out.println("alive");
      showThreadStatus(thrd);
  }

  static void showThreadStatus(Thread thrd) {
    System.out.println(thrd.getName()+" Alive:"+thrd.isAlive()+" State:" + thrd.getState() );
  }
}

   
  








Related examples in the same category

1.Is thread aliveIs thread alive
2.Thread sleepThread sleep
3.Another way to stop a threadAnother way to stop a thread
4.Another way to suspend and resumeAnother way to suspend and resume
5.Visual suspend and resumeVisual suspend and resume
6.Thread sleep and interruptThread sleep and interrupt
7.Daemon ThreadDaemon Thread
8.Pausing the Current Thread: a thread can temporarily stop execution.
9.Pausing a Thread: set a variable that the thread checks occasionally, call Object.wait()
10.set Uncaught Exception Handler
11.Pause the execution
12.Interrupt a thread.
13.Stopping a Thread: set a variable that the thread checks occasionally
14.Determining When a Thread Has Finished
15.Add a delay
16.Pause the execution of a thread using sleep()