簡體   English   中英

拋出新的InterruptedException()代替.join()

[英]Throw new InterruptedException() instead .join()

我嘗試使用.interrupt()方法停止線程。

這是我的代碼:

@Override
public void run() {
    try {

        for (int i = 0; i < 1000000000; i++) {
            System.out.println(threadName + " generated " + i);
            if (counter.isInterrupted()) {
                counter.join();
            }
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
}

我不明白的是,而不是這段代碼:

if (counter.isInterrupted()) {
    counter.join();
}

如果我拋出InterruptedException,它也可以正常工作。

if (counter.isInterrupted()) {
    throw new InterruptedException();
}

我不明白的是為什么我會選擇一個而不是另一個。 我也看到了一些人們也使用易失性布爾變量的方法。 比我的方法安全嗎?

InterruptedException旨在指示當前線程在操作過程中已被中斷。 第二個選項的問題是,您在其他線程被中斷的基礎上引發了異常。 這將導致通過調用代碼產生錯誤的印象。

根據經驗,當您捕獲InterruptedException ,您應該做以下三件事之一:

  • 重新拋出它(沒有包裝異常),以便調用者知道中斷
  • 重新設置interrupt() ,以便保持該線程被中斷的事實
  • 處理中斷(通常通過清理和關閉線程)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM