![](/img/trans.png)
[英]Refactor method to throw at most one checked exception instead of ExecutionException and InterruptedException
[英]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.