CompletableFuture allOf 方法行为

Abh*_*ash 6 java completable-future

我有以下一段java代码:

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return "Result of Future 1";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return "Result of Future 2";
        });

        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return "Result of Future 3";
        });

        boolean isdone = CompletableFuture.allOf(future1, future2, future3).isDone();

        if (isdone) {
            System.out.println("Future result " + future1.get() + " | " + future2.get() + " | " + future3.get());
        } else {
            System.out.println("Futures are not ready");
        }
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时,它总是打印“期货尚未准备好”。我在这里使用 allOf 方法,它应该等待所有 futures 完成,但主线程不会在这里等待并打印 else 部分。有人可以帮我理解这里出了什么问题吗?

Era*_*ran 7

我在这里使用 allOf 方法,它应该等待所有 future 完成

事实并非如此allOf。它创造了一个新CompletableFutureis completed when all of the given CompletableFutures complete。然而,它不会等待新CompletableFuture的完成。

这意味着您应该调用一些等待此CompletableFuture完成的方法,此时所有给定的都CompletableFuture保证完成。

例如:

CompletableFuture<Void> allof = CompletableFuture.allOf(future1, future2, future3);
allof.get();

if (allof.isDone ()) {
    System.out.println("Future result " + future1.get() + " | " + future2.get() + " | " + future3.get());
} else {
    System.out.println("Futures are not ready");
}
Run Code Online (Sandbox Code Playgroud)

输出:

Future result Result of Future 1 | Result of Future 2 | Result of Future 3
Run Code Online (Sandbox Code Playgroud)