Thread.interrupted和Thread.interrupt

interrupt —— 當(dāng)其他線程通過調(diào)用當(dāng)前線程的interrupt方法,表示向當(dāng)前線程打個(gè)招呼,告訴他可以中斷線程的執(zhí)行了,至于什么時(shí)候中斷,取決于當(dāng)前線程自己

@Slf4j
public class InterruptDemo {

  private static int i;
    // while 情況下 interrupt 執(zhí)行有意義
    //線程處于阻塞狀態(tài)下的情況下(中斷才有意義)
  // 阻塞狀態(tài): thread.join  wait  thread.sleep  (從阻塞中喚醒拋出一個(gè)異常來中斷線程)
  
  public static void main(String[] args) {
    Thread thread = new Thread(()->{
      //Thread.currentThread().isInterrupted() 默認(rèn)是false
      //判斷中斷標(biāo)識
      while (!Thread.currentThread().isInterrupted()){
        log.info("I: "+i);
        i++;
        log.info("I: "+i);
      }
    });
    thread.start();
    thread.interrupt();//中斷(友好)

  }
}

Thread.interrupted() 對設(shè)置中斷標(biāo)識的線程復(fù)位,并且返回當(dāng)前的中斷狀態(tài)

 /**
   *   Thread.interrupted(); 對設(shè)置中斷標(biāo)識的線程復(fù)位,并且返回當(dāng)前的中斷狀態(tài)
   * @throws InterruptedException
   */
  public void exp3() throws InterruptedException {
      Thread thread = new Thread(()->{
        while (true){
          if (Thread.currentThread().isInterrupted()){
            log.info("------"+Thread.currentThread().isInterrupted());
            Thread.interrupted();
            log.info("-======+=="+Thread.currentThread().isInterrupted());
          }
        }
      });
      thread.start();
    TimeUnit.SECONDS.sleep(11);
    thread.interrupt();
  }

簡單的理解就是 thread.interrupt();和Thread.interrupted(); 這兩個(gè)就是一個(gè)線程的開關(guān), thread.interrupt()就是將一個(gè)線程關(guān)閉,而Thread.interrupted()就是將受到thread.interrupt()作用的線程給打開阻止其關(guān)閉。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容