Java 实例 - 状态监测


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

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

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

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