我大致有这样的代码:为什么invokeAll()不会返回?
ExecutorService threader = Executors.newFixedThreadPool(queue.size());
List futures = threader.invokeAll(queue);
我这调试的invokeAll和似乎并没有返回,直到队列中的所有线程都完成了。任何这种情况发生的原因。
我大致有这样的代码:为什么invokeAll()不会返回?
ExecutorService threader = Executors.newFixedThreadPool(queue.size());
List futures = threader.invokeAll(queue);
我这调试的invokeAll和似乎并没有返回,直到队列中的所有线程都完成了。任何这种情况发生的原因。
报价执行给定的任务,返回保持状态期货和结果当所有完整的列表。 the API
你必须submit()
逐一时间,而不是,是这样的:
public static <T> List<Future<T>> submitAll (ExecutorService executor, Collection<? extends Callable<T> > tasks) {
List<Future<T>> result = new ArrayList<Future<T>>(tasks.size());
for (Callable<T> task : tasks)
result.add (executor.submit (task));
return result;
}
因为它的设计那样:
[...]
Executes the given tasks, returning a list of Futures holding their status and results when all complete.
[...]
当我们调用invokeAll()
方法返回List<Futute<T>>
对象。 此Future
对象保存所有线程的值,直到它成功执行。 所以当我们试图通过Future<T>
对象迭代时,它首先在内部检查Future<T>.isDone()
[我们可能会或可能不会检查外部] Future<T>.isDone()
。如果它返回true,我们可以迭代对象并可以访问对象的值,否则它会等待直到真实。
注意:如果Future<T>
得到一个错误的对象,它将不允许您迭代该对象。
ExecutorService threader = Executors.newFixedThreadPool(queue.size());
List<Future<T>> listFuture = threader.invokeAll(queue);
for(Future<T> future: listFuture) {
// Here you have the full access to this future object
}