java多線程 interrupt(), interrupted(), isInterrupted()方法區別

來源:互聯網
上載者:User

標籤:定義   實現   private   tor   綜合   stat   dex   比較   虛擬碼   

interrupt()方法: 作用是中斷線程。
  • 本線程中斷自身是被允許的,且"中斷標記"設定為true
  • 其它線程調用本線程的interrupt()方法時,會通過checkAccess()檢查許可權。這有可能拋出SecurityException異常。 
    • 若線程在阻塞狀態時,調用了它的interrupt()方法,那麼它的“中斷狀態”會被清除並且會收到一個InterruptedException異常。 
      • 例如,線程通過wait()進入阻塞狀態,此時通過interrupt()中斷該線程;調用interrupt()會立即將線程的中斷標記設為“true”,但是由於線程處於阻塞狀態,所以該“中斷標記”會立即被清除為“false”,同時,會產生一個InterruptedException的異常。
    • 如果線程被阻塞在一個Selector選取器中,那麼通過interrupt()中斷它時;線程的中斷標記會被設定為true,並且它會立即從選擇操作中返回。
    • 如果不屬於前面所說的情況,那麼通過interrupt()中斷線程時,它的中斷標記會被設定為“true”。
 interrupted()方法

判斷的是當前線程是否處於中斷狀態。是類的靜態方法,同時會清除線程的中斷狀態。

 
1 public static boolean interrupted() {2   return currentThread().isInterrupted(true);3 }
isInterrupted()方法

判斷調用線程是否處於中斷狀態 
例如:

 
public static void main(String[] args){  Thread thread = new Thread(()->{}); //定義一個線程,虛擬碼沒有具體實現  thread.isInterrupted();//判斷thread是否處於中斷狀態,而不是主線程是否處於中斷狀態  Thread.isInterrupted(); //判斷主線程是否處於中斷狀態}
線程停止
  • 通過“中斷標記”終止線程。
 
@Overridepublic void run() {  while (!isInterrupted()) {// 執行任務...  }}

說明:isInterrupted()是判斷線程的中斷標記是不是為true。當線程處於運行狀態,並且我們需要終止它時;可以調用線程的interrupt()方法,使用線程的中斷標記為true,即isInterrupted()會返回true。此時,就會退出while迴圈。 
注意:interrupt()並不會終止處於“運行狀態”的線程!它會將線程的中斷標記設為true。

  • 通過“額外委任標記”。
  
private volatile boolean flag= true;protected void stopTask() {  flag = false;  }  @Override  public void run() {  while (flag) {  // 執行任務...  }}

 

說明:線程中有一個flag標記,它的預設值是true;並且我們提供stopTask()來設定flag標記。當我們需要終止該線程時,調用該線程的stopTask()方法就可以讓線程退出while迴圈。 
注意:將flag定義為volatile類型,是為了保證flag的可見度。即其它線程通過stopTask()修改了flag之後,本線程能看到修改後的flag的值。

 綜合線程處於“阻塞狀態”和“運行狀態”的終止方式,比較通用的終止線程的形式如下: 
@Overridepublic void run() {  try {  // 1. isInterrupted()保證,只要中斷標記為true就終止線程。  while (!isInterrupted()) {  // 執行任務...  }  } catch (InterruptedException ie) {  // 2. InterruptedException異常保證,當InterruptedException異常產生時,線程被終止。  }}

 

java多線程 interrupt(), interrupted(), isInterrupted()方法區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.