Java 实例 - 线程挂起


以下实例演示了如何将线程挂起:

  1. /*
  2. author by shouce.ren
  3. SleepingThread.java
  4. */
  5.  
  6. public class SleepingThread extends Thread {
  7. private int countDown = 5;
  8. private static int threadCount = 0;
  9. public SleepingThread() {
  10. super("" + ++threadCount);
  11. start();
  12. }
  13. public String toString() {
  14. return "#" + getName() + ": " + countDown;
  15. }
  16. public void run() {
  17. while (true) {
  18. System.out.println(this);
  19. if (--countDown == 0)
  20. return;
  21. try {
  22. sleep(100);
  23. }
  24. catch (InterruptedException e) {
  25. throw new RuntimeException(e);
  26. }
  27. }
  28. }
  29. public static void main(String[] args)
  30. throws InterruptedException {
  31. for (int i = 0; i < 5; i++)
  32. new SleepingThread().join();
  33. System.out.println("线程已被挂起");
  34. }
  35. }

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

  1. #1: 5
  2. #1: 4
  3. #1: 3
  4. #1: 2
  5. #1: 1
  6. ……
  7. #5: 3
  8. #5: 2
  9. #5: 1
  10. 线程已被挂起