我大致有这样的代码:
ExecutorService threader = Executors.newFixedThreadPool(queue.size());
List futures = threader.invokeAll(queue);
我调试了这个程序,发现当队列中的所有线程都完成时,invokeAll方法才会返回。您知道为什么会出现这种情况吗?
我大致有这样的代码:
ExecutorService threader = Executors.newFixedThreadPool(queue.size());
List futures = threader.invokeAll(queue);
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>
对象的值,否则它将等待直到变为true。Future<T>
得到一个false对象,它将不允许您迭代该对象。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
}