Java 实例 - 状态监测

以下实例演示了如何通过继承 Thread 类并使用 currentThread.getName() 方法来监测线程的状态:

Main.java 文件

  1. class MyThread extends Thread{
  2. boolean waiting= true;
  3. boolean ready= false;
  4. MyThread() {
  5. }
  6. public void run() {
  7. String thrdName = Thread.currentThread().getName();
  8. System.out.println(thrdName + " starting.");
  9. while(waiting)
  10. System.out.println("waiting:"+waiting);
  11. System.out.println("waiting...");
  12. startWait();
  13. try {
  14. Thread.sleep(1000);
  15. }
  16. catch(Exception exc) {
  17. System.out.println(thrdName + " interrupted.");
  18. }
  19. System.out.println(thrdName + " terminating.");
  20. }
  21. synchronized void startWait() {
  22. try {
  23. while(!ready) wait();
  24. }
  25. catch(InterruptedException exc) {
  26. System.out.println("wait() interrupted");
  27. }
  28. }
  29. synchronized void notice() {
  30. ready = true;
  31. notify();
  32. }
  33. }
  34. public class Main {
  35. public static void main(String args[])
  36. throws Exception{
  37. MyThread thrd = new MyThread();
  38. thrd.setName("MyThread #1");
  39. showThreadStatus(thrd);
  40. thrd.start();
  41. Thread.sleep(50);
  42. showThreadStatus(thrd);
  43. thrd.waiting = false;
  44. Thread.sleep(50);
  45. showThreadStatus(thrd);
  46. thrd.notice();
  47. Thread.sleep(50);
  48. showThreadStatus(thrd);
  49. while(thrd.isAlive())
  50. System.out.println("alive");
  51. showThreadStatus(thrd);
  52. }
  53. static void showThreadStatus(Thread thrd) {
  54. System.out.println(thrd.getName() + "Alive:=" + thrd.isAlive() + " State:=" + thrd.getState());
  55. }
  56. }

以上代码运行输出结果为:

  1. ……
  2. alive
  3. alive
  4. MyThread #1 terminating.
  5. alive
  6. ……