Java 实例 - 终止线程


Java中原来在Thread中提供了stop()方法来终止线程,但这个方法是不安全的,所以一般不建议使用。

本文向大家介绍使用interrupt方法中断线程。

使用interrupt方法来终端线程可分为两种情况:

  • (1)线程处于阻塞状态,如使用了sleep方法。
  • (2)使用while(!isInterrupted()){……}来判断线程是否被中断。

在第一种情况下使用interrupt方法,sleep方法将抛出一个InterruptedException例外,而在第二种情况下线程将直接退出。下面的代码演示了在第一种情况下使用interrupt方法。

  1. /*
  2. author by shouce.ren
  3. ThreadInterrupt.java
  4. */
  5.  
  6. public class ThreadInterrupt extends Thread
  7. {
  8. public void run()
  9. {
  10. try
  11. {
  12. sleep(50000); // 延迟50秒
  13. }
  14. catch (InterruptedException e)
  15. {
  16. System.out.println(e.getMessage());
  17. }
  18. }
  19. public static void main(String[] args) throws Exception
  20. {
  21. Thread thread = new ThreadInterrupt();
  22. thread.start();
  23. System.out.println("在50秒之内按任意键中断线程!");
  24. System.in.read();
  25. thread.interrupt();
  26. thread.join();
  27. System.out.println("线程已经退出!");
  28. }
  29. }

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

  1. 50秒之内按任意键中断线程!
  2.  
  3. sleep interrupted
  4. 线程已经退出!