如何取消Java 8可完成的未来?
我正在玩Java 8可兼容的未来。我有以下代码:
CountDownLatch waitLatch = new CountDownLatch(1);
CompletableFuture<?> future = CompletableFuture.runAsync(() -> {
try {
System.out.println("Wait");
waitLatch.await(); //cancel should interrupt
System.out.println("Done");
} catch (InterruptedException e) {
System.out.println("Interrupted");
throw new RuntimeException(e);
}
});
sleep(10); //give it some time to start (ugly, but works)
future.cancel(true);
System.out.println("Cancel called");
assertTrue(future.isCancelled());
assertTrue(future.isDone());
sleep(100); //give it some time to finish
使用 runAsync,我计划执行在闩锁上等待的代码。接下来,我取消了未来,期望在内部抛出中断的异常。但是,线程似乎在 await 调用时仍然被阻塞,并且即使取消了未来(断言通过),也永远不会引发 InterruptedException。使用 ExecutorService 的等效代码按预期工作。它是CompletableFuture中的错误还是我的例子中的错误?