轉自:http://jay-kid.iteye.com/blog/557064
在《Java網路編程》上看到一個例子, 說是用thread.interrupt()去關閉在等待的線程。不太明白,於是去查了一下Java的API。
有興趣的同行們可以先看看API的內容,再看以下總結:
1. thread.isInterrupt()和Thread.interrupted()都返回當前線程interrupt的狀態
- thread.isInterrupt()是非靜態函數,作用目標是“線程執行個體”,一般用法如下,
Java代碼
- TestInterrupt t = new TestInterrupt();
- t.start();
- System.out.println(t.isInterrupt());
- 而Thread.interrupted()是靜態函數,作用目標是“當前線程”
Java代碼
- System.out.println(Thread.interrupted());
並且它會把當前線程的interrupt狀態“複位”,假設當前線程的isInterrupt狀態為true,它會返回true,但過後isInterrupt的狀態會複位為false。之後調用(Thread)t.isInterrupt或Thread.interrupted都會返回false
2. interrupt()被調用後有幾個可能,下面挑幾種常見的歸類一下:
線程阻塞的情況下:
- 如果線程在調用
Object 類的 wait()、wait(long) 或 wait(long, int) 方法,或者該類的join()、join(long)、join(long, int)、sleep(long) 或 sleep(long, int) 方法過程中受阻,則其isInterrupt狀態將被清除,設成false, 它還將收到一個InterruptedException.
Java代碼
- public void run() {
-
- while (!Thread.currentThread().isInterrupted()) {
- try{
- Thread.sleep(1000);
- } catch (InterruptedException ie){
- ie.printStackTrace();
- }
- }
- }
如上所示,如果線程運行到Thread.sleep(1000)時,被其他線調用了該線程的interrupt()的方法,它將會進入catch的段落裡面,然後再運行while (!Thread.currentThread().isInterrupted()) 時退出run, 線程被銷毀。
- 如果該線程在可中斷的通道上的 I/O 操作中受阻,則該通道將被關閉,該線程的isInterrupt狀態將被設定成true, 並且該線程將收到一個
ClosedByInterruptException。
線程正常啟動並執行情況下:
- 該線程不受影響,繼續運行,但該線程的isInterrupt狀態將被設定成true
Java代碼
- public void run() {
-
- while (!Thread.currentThread().isInterrupted()) {
- try{
- //A: 無阻塞的代碼.......
- ......
- //B: 被調用interrupt.......
- ......
- //C: 無阻塞的代碼.......
- } catch (InterruptedException ie){
- ie.printStackTrace();
- }
- }
- }
如上所示, 當線程正常運行時,在運行到B點時被調用了interrupt(), 此時該線程將繼續正常運行,但isInterrupt的狀態會被設為true,當做完 A,B,C的代碼時,再進入while (!Thread.currentThread().isInterrupted()) 時,該線程被銷毀。假如while的檢查條件改為(true),該線程不會受影響,將會一直運行下去。