Thread 類中提供了兩種方法用來判斷線程的狀態是不是停止的。就是我們今天的兩位主人公 interrupted() 和 isInterrupted() 。
interrupted()

官方解釋:測試當前線程是否已經中斷,當前線程是指運行 this.interrupted() 方法的線程 。
public class t12 { public static void main(String[] args) { try { MyThread12 thread = new MyThread12(); thread.start(); Thread.sleep(500); thread.interrupt(); System.out.println("是否終止1? =" + thread.interrupted()); System.out.println("是否終止2? =" + thread.interrupted()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("-------------end-------------"); } } class MyThread12 extends Thread { public void run() { for (int i = 0; i < 50000; i++) { System.out.println("i = " + i); } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24

程序運行結束后,結果如上圖所示,thread 線程並沒有停止,而且調用 thread.interrupted() 結果是兩個 false 表示線程一直在運行過程中,為什么會出現這種結果呢?
讓我們再來自己看看官方解釋,這次請着重閱讀我標紅的文字:當前線程是指運行 this.interrupted() 方法的線程 。也就是說,當前線程並不是 thread,並不是因為 thread 調用了 interrupted() 方法就是當前線程。當前線程一直是 main 線程,它從未中斷過,所以打印結果就是兩個 false。
那么如何讓 main 線程產生中斷效果呢?
public class t13 { public static void main(String[] args) { Thread.currentThread().interrupt(); System.out.println("是否終止1? =" + Thread.interrupted()); System.out.println("是否終止2? =" + Thread.interrupted()); System.out.println("----------end-----------"); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9

從上述結果中可以看出,方法 interrupted() 的確判斷出當前線程是否已經停止,但是為什么第 2 個布爾值是 false 呢?讓我們重新閱讀一次文檔。

你看,文檔中說的很詳細,interrupted() 方法具有清除狀態的功能,所以第二次的時候返回值是 false。
isInterrupted()

從聲明中可以看出來 isInterrupted() 方法並不是 static 的。並且 isInterrupted() 方法並沒有清除狀態的功能。
public class t14 { public static void main(String[] args) { try { MyThread14 thread = new MyThread14(); thread.start(); Thread.sleep(1000); //此方法代表 讓當前線程休眠 1 秒,即表示使 main線程休眠 1秒 thread.interrupt(); System.out.println("是否終止1? =" + thread.isInterrupted()); System.out.println("是否終止2? =" + thread.isInterrupted()); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("----------end-----------"); } } class MyThread14 extends Thread { public void run() { for (int i = 0; i < 500000; i++) { System.out.println("i = " + i); } } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24

總結
1. interrupted():測試 當前線程 是否已經是中斷狀態,執行后具有清除狀態功能。
2. isInterrupted():測試線程 Thread 對象 是否已經是中斷狀態,但不清楚狀態標志。
