1. 程式人生 > >java多線程 interrupt(), interrupted(), isInterrupted()方法區別

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

while循環 vid 選擇器 狀態 任務 col acc color 設置

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(); //判斷主線程是否處於中斷狀態
}

線程停止

  • 通過“中斷標記”終止線程。
@Override
public void run() {
  while (!isInterrupted()) {
// 執行任務...   } }

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

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

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

綜合線程處於“阻塞狀態”和“運行狀態”的終止方式,比較通用的終止線程的形式如下:

@Override
public void run() {
  try {
  // 1. isInterrupted()保證,只要中斷標記為true就終止線程。
  while (!isInterrupted()) {
  // 執行任務...
  }
  } catch (InterruptedException ie) {
  // 2. InterruptedException異常保證,當InterruptedException異常產生時,線程被終止。
  }
}

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