gpt4 book ai didi

java - 一次收集几个 Future 的结果(即加入)

转载 作者:行者123 更新时间:2023-12-01 12:08:17 25 4
gpt4 key购买 nike

我有一个线程池,可以为各种任务创建 future 。有时,我需要加入,例如3 个这样的 future 集中在一处。例如:

Future f1 = asyncRun("one");
Future f2 = asyncRun("two");
Future f3 = asyncRun("three");

在代码的后面,我有一点必须获得所有 3 个结果。我正在考虑制作一个 util 方法,我能想到的最好的方法是:

public static <V> V[] get(Class<V> type, Future<V>... futures) throws ExecutionException, InterruptedException {
V[] values = (V[]) Array.newInstance(type, futures.length);

for (int i = 0; i < futures.length; i++) {
Future<V> future = futures[i];
values[i] = future.get();
}
return values;
}

这很丑陋,因为我需要为 future 的值提供类名称。

还有更好的主意吗?

最佳答案

你必须通过Class<V>的原因实际上与并发或 future 没有任何关系,这只是因为您想返回泛型类型的数组。遗憾的是,数组和泛型在 Java 中不能很好地协同工作。

您可以返回 List<V>而不是数组:

public static <V> List<V> get(Future<V>... futures) throws ExecutionException, InterruptedException {
List<V> values = new ArrayList<>();
for (int i = 0; i < futures.length; i++){
values.add(futures[i].get());
}

return values;
}

如果你绝对想要一个数组,那么你可以在调用时以通常的方式转换它:

Future<String> f1 = asyncRun("one");
Future<String> f2 = asyncRun("two");
Future<String> f3 = asyncRun("three");

String[] result = get(f1, f2, f3).toArray(new String[3]);

关于java - 一次收集几个 Future 的结果(即加入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27424307/

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