2 回答

TA貢獻1884條經驗 獲得超4個贊
拋出異常后會清除中斷標記位,調用Thread.currentThread.interrupt()重新設置中斷狀態(tài),讓調用方知道是由于中斷才結束線程的。
比如你上面的代碼,sleep響應了中斷,當線程在seep中的時候,如果這個時候有中斷的請求,就會拋出InterruptedException異常,并且清除中斷狀態(tài),所以我們有時候需要再置為中斷狀態(tài)(其實就是需要保持這個中斷狀態(tài))。
public class Test {
public static int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread th = new Thread(){
@Override
public void run() {
while(true){
if(Thread.currentThread().isInterrupted()){//(1)
System.out.println("Thread Interrupted");
break;
}
System.out.println("invoking!!!");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Interruted When Sleep");
//拋出異常后會清除中斷標記位,所以需要重新設置中斷狀態(tài),讓(1)出的代碼可以檢測到中斷結束線程
Thread.currentThread().interrupt();
}
}
}
};
th.start();
Thread.currentThread().sleep(1000);
th.interrupt();
}
}
打印結果:
invoking!!!
Interruted When Sleep
Thread Interrupted
添加回答
舉報