Java thread的Interrupt, isInterrupt, interrupted

來源:互聯網
上載者:User

轉自:http://jay-kid.iteye.com/blog/557064

在《Java網路編程》上看到一個例子, 說是用thread.interrupt()去關閉在等待的線程。不太明白,於是去查了一下Java的API。 

有興趣的同行們可以先看看API的內容,再看以下總結:

 

1. thread.isInterrupt()和Thread.interrupted()都返回當前線程interrupt的狀態

  • thread.isInterrupt()是非靜態函數,作用目標是“線程執行個體”,一般用法如下,
Java代碼  
  1. TestInterrupt t = new TestInterrupt();  
  2. t.start();  
  3. System.out.println(t.isInterrupt());  

 

  • 而Thread.interrupted()是靜態函數,作用目標是“當前線程”
Java代碼  
  1. 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代碼  
  1. public void run() {  
  2.   
  3.     while (!Thread.currentThread().isInterrupted()) {  
  4.         try{  
  5.             Thread.sleep(1000);  
  6.         } catch (InterruptedException ie){  
  7.             ie.printStackTrace();  
  8.         }  
  9.     }  
  10. }  

 如上所示,如果線程運行到Thread.sleep(1000)時,被其他線調用了該線程的interrupt()的方法,它將會進入catch的段落裡面,然後再運行while (!Thread.currentThread().isInterrupted()) 時退出run, 線程被銷毀。

 

  • 如果該線程在可中斷的通道上的 I/O 操作中受阻,則該通道將被關閉,該線程的isInterrupt狀態將被設定成true, 並且該線程將收到一個 ClosedByInterruptException。 

 

 

線程正常啟動並執行情況下:

  •  該線程不受影響,繼續運行,但該線程的isInterrupt狀態將被設定成true
Java代碼  
  1. public void run() {  
  2.   
  3.     while (!Thread.currentThread().isInterrupted()) {  
  4.         try{  
  5.             //A: 無阻塞的代碼.......  
  6.             ......  
  7.             //B: 被調用interrupt.......  
  8.             ......  
  9.             //C: 無阻塞的代碼.......  
  10.         } catch (InterruptedException ie){  
  11.             ie.printStackTrace();  
  12.         }  
  13.     }  
  14. }  

 如上所示, 當線程正常運行時,在運行到B點時被調用了interrupt(), 此時該線程將繼續正常運行,但isInterrupt的狀態會被設為true,當做完 A,B,C的代碼時,再進入while (!Thread.currentThread().isInterrupted()) 時,該線程被銷毀。假如while的檢查條件改為(true),該線程不會受影響,將會一直運行下去。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.