Thread interrupted() 線程的中斷


問題:

  1、線程的中斷方式。

  2、為什么中斷阻塞中的線程,會拋出異常。

代碼示例:  

package com.hdwl.netty;

public class ThreadInterrupted {

  public static void main(String[] args) {
//    testNoInterrupted();
//    testInterrupted();
    testInterruptedWithBlock();
  }

  //測試阻塞線程的中斷
  private static void testInterruptedWithBlock() {
    MyInterruptedBlockThread mibt = new MyInterruptedBlockThread();
    mibt.start();
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    mibt.interrupt();//設置中斷標示
  }

  //線程非阻塞中斷的演示
  private static void testInterrupted() {
    MyInterruptedNoBlockThread mibt = new MyInterruptedNoBlockThread();
    mibt.start();
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    mibt.interrupt();//設置線程中斷標示
  }

  //不中斷線程的演示,由於未設置中斷標示,所有線程永遠不會中斷。
  private static void testNoInterrupted() {
    MyInterruptedNoBlockThread mibt = new MyInterruptedNoBlockThread();
    mibt.start();
  }

}
//阻塞線程
class MyInterruptedBlockThread extends Thread{
  @Override
  public void run() {
    //如果線程中斷位置為true,則結束while循環
    while (!isInterrupted()){
      System.out.println("running……");
      try {
        sleep(2000);
      } catch (InterruptedException e) {
        e.printStackTrace();
        //當阻塞中的線程被中斷,線程的中斷標示被重置,所以需要重新設置
        interrupt();
      }
    }
    System.out.println("線程結束!");
  }
}
//非阻塞線程
class MyInterruptedNoBlockThread extends Thread{
  @Override
  public void run() {
    //如果線程中斷位置為true,則結束while循環
    while (!isInterrupted()){
      System.out.println("running……");
    }
    System.out.println("線程結束!");
  }
}

解答問題:

  1、線程的中斷,使用設置中斷標示的方式進行。

  2、中斷阻塞中的線程拋出異常,是為了不讓線程無休止的中斷。因為設置中斷標示,線程並不會馬上停止,還需要等待下一次的CPU時間片到來,才能根據interrupted方法的返回值來終止線程。如果某個阻塞線程B,依賴於線程A的notify(或者其它操作,才能喚醒線程B),那么將線程A,B同時設置為中斷標示,此時線程A已經死亡了,而線程B還一直等到喚醒,才能根據interrupted方法,進行線程的中斷操作。因此,中斷阻塞中的線程,必須拋出異常,方便我們進行后續的處理。

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM