gpt4 book ai didi

java - 等待 List 中的每个 Future 完成

转载 作者:行者123 更新时间:2023-11-29 06:27:55 25 4
gpt4 key购买 nike

<分区>

我调用了一个返回 Future 的方法, 对于 List<Principal> 中的每个元素一次,所以我最终得到一个 List<Future<UserRecord>> .

方法返回Future是库代码,我无法控制该代码的运行方式,我只有 Future .

我想等待所有Future在继续之前完成(成功或失败)。

有没有比这更好的方法:

List<Principal> users = new ArrayList<>();
// Fill users
List<Future<UserRecord>> futures = getAllTheFutures(users);
List<UserRecord> results = new ArrayList<>(futures.size());
boolean[] taskCompleted = new boolean[futures.size()];
for (int j = 0; j < taskCompleted.length; j++) {
taskCompleted[j] = false;
}
do {
for (int i = 0; i < futures.size(); i++) {
if (!taskCompleted[i]) {
try {
results.add(i, futures.get(i).get(20, TimeUnit.MILLISECONDS));
taskCompleted[i] = true;
} catch (TimeoutException e) {
// Do nothing
} catch (InterruptedException | ExecutionException e) {
// Handle appropriately, then...
taskCompleted[i] = true;
}
}
}
} while (allNotCompleted(taskCompleted));

对于好奇的人:

private boolean allNotCompleted(boolean[] completed) {
for (boolean b : completed) {
if (!b)
return true;
}
return false;
}

不同于对 Waiting on a list of Future 的回答我无法控制创建 Future 的代码

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