CompletableFuture allOf方法行为

时间:2018-11-20 10:34:07

标签: 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");
        }

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

1 个答案:

答案 0 :(得分:2)

  

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

这不是allOf所做的。它将创建一个新的CompletableFuture is 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");
}

输出:

Future result Result of Future 1 | Result of Future 2 | Result of Future 3