Java 实例 - 线程挂起

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

SleepingThread.java 文件

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

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

  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. 线程已被挂起