[英]Java: if joining Threads does not work: break or continue?
如果連接線程無效,建議怎么辦?
for (List t : threads) {
try {
t.join();
} catch (InterruptedException e) {
log.error("Thread " + t.getId() + " interrupted: " + e);
// and now?
}
}
是建議先中斷(然后與尚未連接的其他線程發生什么情況?),還是應該至少嘗試加入其余線程然后繼續?
感謝您的建議!
==> 結論 :您應再次嘗試加入特定線程t或中斷該特定線程t並繼續。
for (List t : threads) {
try {
t.join();
} catch (InterruptedException e) {
try {
// try once! again:
t.join();
} catch (InterruptedException ex) {
// once again exception caught, so:
t.interrupt();
}
}
}
那么您如何看待該解決方案? 並且正確執行“ t.interrupt()”還是應該為Thread.currentThread()。interrupt(); ?
謝謝! :-)
之所以得到InterruptedException
是因為其他線程中斷了該線程(即連接線程),而不是因為該join
沒有“起作用”。 引用自API文檔 :
InterruptedException
如果另一個線程中斷了當前線程。 引發此異常時,將清除當前線程的中斷狀態。
我建議您重新加入該線程 ,例如:
for (List t : threads) {
while (true) {
try {
t.join();
break;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// ... and ignore the interrupt
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.