当另一组 CompletableFuture 完成时,你如何完成一个 CompletableFuture?

How do you complete a CompletableFuture when another set of CompletableFutures is complete?

我有一个可完成的未来 (future1),它创建了 10 个可完成的未来 (futureN)。只有当所有 futureN 都完成时,有没有办法将 future1 设置为完成?

我不确定你所说的 "future creates other futures" 是什么意思,但是如果你有很多未来并且你想在它们完成后做某事,你可以这样做: CompletableFuture.allOf(future2, future3, ..., futureN).thenRun(() -> future1.complete(value));

A CompletableFuture 不是 行为 所以我不确定你所说的

是什么意思

which create 10 completable futures

我假设您的意思是您使用 runAsyncsubmitAsync 提交了任务。我的示例不会,但如果您这样做,行为是相同的。

创建您的根 CompletableFuture. Then run some code asynchronously that creates your futures (through an Executor, runAsync, inside a new Thread, or inline with CompletableFuture return values). Collect the 10 CompletableFuture objects and use CompletableFuture#allOf to get a CompletableFuture that will complete when they are all complete (exceptionally or otherwise). You can then add a continuation to it with 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();
}