Java 实例 - 中断线程


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

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

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

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