gpt4 book ai didi

java - CompletableFuture allOf 方法行为

转载 作者:行者123 更新时间:2023-12-03 23:14:44 26 4
gpt4 key购买 nike

我有以下一段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");
}

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

最佳答案

I am using allOf method here which should wait for all the futures to get completed



那不是什么 allOf做。它创建了一个新的 CompletableFuture那个 is completed when all of the given CompletableFutures complete .但是,它不会等待新的 CompletableFuture去完成。

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

例如:
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

关于java - CompletableFuture allOf 方法行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53391071/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com