java一次收集少量期货(即join)的结果
我有一个线程池,可以为各种任务创建未来。有时,我需要在一个地方加入例如3个这样的未来。例如:
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;
}
这很难看,因为我需要为将来的值提供类名
还有更好的主意吗
# 1 楼答案
必须传递
Class<V>
的原因实际上与并发性或未来无关,只是因为要返回泛型类型的数组。不幸的是,数组和泛型在Java中不能很好地协同工作可以返回
List<V>
而不是数组:如果你绝对想要一个数组,那么你可以用通常的方式在你称之为:
# 2 楼答案
返回列表而不是数组
或者,您可以从获得的第一个对象中获取类引用:
Class<V> type = futures[0].get().getClass()