我已經嘗試查看其他執行緒,但我似乎無法找到正確的答案,
使用 executorService.shutdownNow() 時,幾乎所有任務都會按預期立即停止,除了那些帶有 for 回圈的任務。我不知道它為什么會發生,但我從其他執行緒中看到的最多的是你應該使用 Thread.currentThread().isInterrupted() 來檢查它是否被中斷,但是添加一個
if(Thread.currentThread().isInterrupted())
{return;}
實際上并沒有阻止這一切。當關閉 UI 按鈕時,我正在呼叫執行程式 shutdownNow。
代碼示例:
executorService.submit(() -> {
ctx.batzUtils.keyEvent(KeyEvent.KEY_PRESSED, VK_SHIFT);
//Shit keeps going if you call ShutdownNow Todo
for (Rectangle rect : rects)
{
ctx.batzUtils.click(rect);
try
{
Thread.sleep(minDelayBetween, maxDelayBetween);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
ctx.batzUtils.keyEvent(KeyEvent.KEY_RELEASED, VK_SHIFT);
ctx.batzUtils.keyEvent(KeyEvent.KEY_TYPED, VK_SHIFT);
});
任何關于為什么或解決方案的想法將不勝感激
uj5u.com熱心網友回復:
2 解決方案。你的 for 回圈你確實需要檢查
if(Thread.currentThread().isInterrupted()) {[clean up and finish the thread code here]}
在您的catch部分中,而不是e.printStackTrace();放置 [清理并完成執行緒代碼]。在 catch 陳述句中,您不需要檢查執行緒是否已被中斷。您捕獲 InterruptedException 的事實已經是執行緒已被中斷的標志
uj5u.com熱心網友回復:
在我的 catch 陳述句中添加 Thread.currentThread().interrupt() 有效
歸功于@Sambit
uj5u.com熱心網友回復:
使用 executorService.shutdownNow() 時,幾乎所有任務都會按預期立即停止,除了那些帶有 for 回圈的任務。
這是一種誤導性的說法。executorService.shutdownNow()取消任何尚未運行的作業并中斷當前正在運行的所有執行緒。您的某些執行緒沒有被中斷的原因是因為您正在捕獲InterruptedExceptionfor 回圈。每當InterruptedException被拋出時,正在運行的執行緒的中斷位被清除。
每當您 catchInterruptedException時,您應該立即重新中斷正在運行的執行緒,以便呼叫者知道已設定中斷。您的錯誤是為什么需要這種模式的一個很好的例子。
try {
Thread.sleep(minDelayBetween, maxDelayBetween);
} catch (InterruptedException e) {
// when InterruptedException is thrown it clears the interrupt bit so
// we need to re-interrupt the thread whenever we catch it
Thread.currentThread().interrupt();
// you should handle the interrupt appropriately and not just print it
return;
}
這是關于Java 執行緒中斷主題的一個很好的教程。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/424590.html
