亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

線程的中斷狀態

線程的中斷狀態

慕桂英4014372 2018-08-10 18:34:16
void mySubTask(){try{sleep(delay)}catch(InterruptedException e){Thread.currentThread.interrupt();} }這串代碼是《java核心技術》中并發一節的。14.2中斷線程,634頁。當線程處于阻塞狀態時,對其發送一個中斷信號,會導致拋出InterruptedException異常。那么以上代碼,在捕捉了這個異常后為什么還要對其設置中斷狀態呢?換句話說,這里設置中斷狀態,意義何在呢?
查看完整描述

2 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

拋出異常后會清除中斷標記位,調用Thread.currentThread.interrupt()重新設置中斷狀態,讓調用方知道是由于中斷才結束線程的。

比如你上面的代碼,sleep響應了中斷,當線程在seep中的時候,如果這個時候有中斷的請求,就會拋出InterruptedException異常,并且清除中斷狀態,所以我們有時候需要再置為中斷狀態(其實就是需要保持這個中斷狀態)。

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");                        //拋出異常后會清除中斷標記位,所以需要重新設置中斷狀態,讓(1)出的代碼可以檢測到中斷結束線程
                        Thread.currentThread().interrupt();
                    }

                }
            }
        };
        th.start();
        Thread.currentThread().sleep(1000);
        th.interrupt();
    }
}
打印結果:
invoking!!!
Interruted When Sleep
Thread Interrupted


查看完整回答
反對 回復 2018-08-12
?
暮色呼如

TA貢獻1853條經驗 獲得超9個贊

wait中拋出InterruptedException 會消耗此線程的中斷狀態

再中斷一次可能是為了向外傳遞?


查看完整回答
反對 回復 2018-08-12
  • 2 回答
  • 0 關注
  • 719 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號