赞
踩
和完成异常类似,我们可以调用cancel(boolean mayInterruptIfRunning)
取消计算。对于CompletableFuture类,布尔参数并没有被使用,这是因为它并没有使用中断去取消操作,相反,cancel
等价于completeExceptionally(new CancellationException())
。
- static void cancelExample() {
- CompletableFuture cf = CompletableFuture.completedFuture("message").thenApplyAsync(String::toUpperCase,
- CompletableFuture.delayedExecutor(1, TimeUnit.SECONDS));
- CompletableFuture cf2 = cf.exceptionally(throwable -> "canceled message");
- assertTrue("Was not canceled", cf.cancel(true));
- assertTrue("Was not completed exceptionally", cf.isCompletedExceptionally());
- assertEquals("canceled message", cf2.join());
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。