[英]How do you complete a CompletableFuture when another set of CompletableFutures is complete?
我有一个可完成的未来(future1),它创造了10个可完成的期货(futureN)。 有没有办法在所有futureN完成后将future1设置为完成?
我不确定你的意思是“未来创造其他未来”,但如果你有许多未来并且你想在完成后做某事你可以这样做: CompletableFuture.allOf(future2, future3, ..., futureN).thenRun(() -> future1.complete(value));
CompletableFuture
不是那种行为,所以我不确定你的意思
这创造了10个可完成的期货
我假设您的意思是您使用runAsync
或submitAsync
提交了任务。 我的例子不会,但如果你这样做,行为是一样的。
创建根CompletableFuture
。 然后异步运行一些代码来创建你的未来(通过Executor
, runAsync
,在新的Thread
内部,或者使用CompletableFuture
返回值内联)。 收集10个CompletableFuture
对象,并使用CompletableFuture#allOf
获取CompletableFuture
,它将在完成后完成(异常或其他方式)。 然后,您可以使用thenRun
为其添加延续以完成您的根未来。
例如
public static void main(String args[]) throws Exception {
CompletableFuture<String> root = new CompletableFuture<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
CompletableFuture<String> cf1 = CompletableFuture.completedFuture("first");
CompletableFuture<String> cf2 = CompletableFuture.completedFuture("second");
System.out.println("running");
CompletableFuture.allOf(cf1, cf2).thenRun(() -> root.complete("some value"));
});
// once the internal 10 have completed (successfully)
root.thenAccept(r -> {
System.out.println(r); // "some value"
});
Thread.sleep(100);
executor.shutdown();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.