這已經困擾了我幾個小時了。如果我安排一個任務在5秒內執行,然后立即取消該任務,我會期望“awaitTermination”方法立即返回,但它會在整個7秒(而不是5秒)內保持阻塞。下面是一個 JUnit 5 測試用例,它在 Java 11 上重現了這個問題。package dummy;import org.junit.jupiter.api.DisplayName;import org.junit.jupiter.api.Test;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;import static org.junit.jupiter.api.Assertions.assertFalse;import static org.junit.jupiter.api.Assertions.fail;class DummyTest { @Test @DisplayName("Cancelling task should work...") void cancel_task() throws InterruptedException { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); AtomicBoolean isExecuted = new AtomicBoolean(false); ScheduledFuture<?> scheduled = executorService.schedule(() -> isExecuted.set(true), 5, TimeUnit.SECONDS); scheduled.cancel(false); if (!executorService.awaitTermination(7, TimeUnit.SECONDS)) { fail("Didn't shut down within timeout"); // <-- Fails here } assertFalse(isExecuted.get(), "Task should be cancelled before executed"); }}有什么想法嗎?
1 回答

嚕嚕噠
TA貢獻1784條經驗 獲得超7個贊
您不會在執行器服務上調用 shutdown 或 shutdownNow,因此您可以永遠等待。它永遠不會終止。首先調用關閉,然后單元測試應該可以正常工作。
scheduled.cancel(false);
executorService.shutdown(); // This was missing
if (!executorService.awaitTermination(7, TimeUnit.SECONDS)) {
...
等待終止“阻止所有任務在關閉請求后完成執行,或者發生超時,或者當前線程中斷,以先發生者為準”(從評論中復制,感謝 ptomli)。
添加回答
舉報
0/150
提交
取消