[英]How to wait for a list of Futures to complete
I have a list of Futures and I want to have every task completed before doing the next step. 我有一份期货清单,我想在完成下一步之前完成所有任务。 Currently I'm doing this:
目前我这样做:
public static int[] benchmark(){
List<Future<Integer>> futureNumbers = service.invokeAll(callableList);
int[] numbers = new int[events.size()];
int i = 0;
for (Future<Integer> future : futureNumbers) {
numbers[i] = future.get();
}
return numbers;
}
But then only the first value of the array I get back is right, the others are 0. How can I achieve that numbers
is just returned when every task has finished? 但是之后只有我得到的数组的第一个值是正确的,其他的是0.我怎样才能实现这些
numbers
只是在每个任务完成后返回?
Your help would be appreciated. 非常感谢您的帮助。
As per Java specs for invokeAll()
method, List<Future<T>>
will contain the result of all tasks and you will get Future
only when all your threads are finished, either normally or because of exception. 根据
invokeAll()
方法的Java规范, List<Future<T>>
将包含所有任务的结果,只有在所有线程完成时,无论是正常还是异常,您都将获得Future
。
So, your Future object should have all the results. 因此,您的Future对象应该具有所有结果。
Executes the given tasks, returning a list of Futures holding their status and results when all complete.
执行给定的任务,返回完成所有状态和结果的Futures列表。
Possibilities: 可能性:
call()
method in try-catch
and print the stack-trace from catch. call()
在try-catch
包含call()
方法的所有代码,并从catch中打印堆栈跟踪。 You will know if there is some exception. Future
object. Future
对象中没有得到任何东西。 Verification step: 验证步骤:
isDone()
- Returns true if this task completed. isDone()
- 如果此任务完成,则返回true。 Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true. 完成可能是由于正常终止,异常或取消 - 在所有这些情况下,此方法将返回true。
for (Future<Integer> future : futureNumbers) {
System.out.println(future.isDone());
numbers[i] = future.get();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.