shutdownNow關不掉線程

@Override
public void run() {

    try {
        while (!Thread.interrupted()) {
            while (!car.waxOn) {
                car.waxOn();
            }
        }
    } catch (InterruptedException e) {
        System.out.println("waxon interrupted");
    }

}

@Override
public void run() {
    while (!Thread.interrupted()) {
        while (!car.waxOn) {
            try {

                car.waxOn();

            } catch (InterruptedException e) {
                System.out.println("waxon interrupted");
            }
        }
    }
}

上下兩個run方法比較,while (!Thread.interrupted()) 判斷應該放在try代碼快裏。否則像下面的寫法,catch會吞掉InterruptedException,到時判斷檢測不出來以至於shutdownNow關不掉線程

shutdownNow的原理是爲每個線程調用 interruput方法,然後有run方法裏的判斷語句來檢查Thread.interrupted()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章