我有以下一段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部分。有人可以帮我了解这里出了什么问题吗?
答案 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