这已经困扰了我几个小时了。如果我安排一个任务在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");
}
}
有什么想法吗?
噜噜哒
相关分类