第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

線程的中斷狀態(tài)

線程的中斷狀態(tài)

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

2 回答

?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

wait中拋出InterruptedException 會消耗此線程的中斷狀態(tài)

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


查看完整回答
反對 回復 2018-08-06
?
慕村9548890

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


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

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

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

公眾號

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