简体   繁体   English

如何等待期货清单完成

[英]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: 可能性:

  1. Probably what could be happening is that some of your thread is aborting because of exception, so call() method is not able to return you the desired result. 可能发生的事情是你的某些线程由于异常而中止,所以call()方法无法返回所需的结果。 Also, since it is a new thread of execution you will not see the exception propagated. 此外,由于它是一个新的执行线程,您将看不到传播的异常。
    So, to counter / manage this, enclose all your code of 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. 你会知道是否有一些例外。
  2. Another possibility could be that some of your Callable implementations are not returning anything, and could be just void, because of which you are not getting anything in Future object. 另一种可能性是你的一些Callable实现没有返回任何东西,并且可能只是void,因为你在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM