Java 实例 - 中断线程

以下实例演示了如何使用interrupt()方法来中断线程并使用 isInterrupted() 方法来判断线程是否已中断:

Main.java 文件

  1. public class Main extends Object
  2. implements Runnable {
  3. public void run() {
  4. try {
  5. System.out.println("in run() - 将运行 work2() 方法");
  6. work2();
  7. System.out.println("in run() - 从 work2() 方法回来");
  8. }
  9. catch (InterruptedException x) {
  10. System.out.println("in run() - 中断 work2() 方法");
  11. return;
  12. }
  13. System.out.println("in run() - 休眠后执行");
  14. System.out.println("in run() - 正常离开");
  15. }
  16. public void work2() throws InterruptedException {
  17. while (true) {
  18. if (Thread.currentThread().isInterrupted()) {
  19. System.out.println("C isInterrupted()=" + Thread.currentThread().isInterrupted());
  20. Thread.sleep(2000);
  21. System.out.println("D isInterrupted()=" + Thread.currentThread().isInterrupted());
  22. }
  23. }
  24. }
  25. public void work() throws InterruptedException {
  26. while (true) {
  27. for (int i = 0; i < 100000; i++) {
  28. int j = i * 2;
  29. }
  30. System.out.println("A isInterrupted()=" + Thread.currentThread().isInterrupted());
  31. if (Thread.interrupted()) {
  32. System.out.println("B isInterrupted()=" + Thread.currentThread().isInterrupted());
  33. throw new InterruptedException();
  34. }
  35. }
  36. }
  37. public static void main(String[] args) {
  38. Main si = new Main();
  39. Thread t = new Thread(si);
  40. t.start();
  41. try {
  42. Thread.sleep(2000);
  43. }
  44. catch (InterruptedException x) {
  45. }
  46. System.out.println("in main() - 中断其他线程");
  47. t.interrupt();
  48. System.out.println("in main() - 离开");
  49. }
  50. }

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

  1. in run() - 将运行 work2() 方法
  2. in main() - 中断其他线程
  3. in main() - 离开
  4. C isInterrupted()=true
  5. in run() - 中断 work2() 方法