Java:带有Callables的ExecutorService:invokeAll()和future.get() – 结果是否正确?

我使用Java中的ExecutorService来调用带有invokeAll()线程。 之后,我使用future.get()获取结果集。 以我创建线程的相同顺序收到结果非常重要。

这是一个片段:

 try { final List threads = new ArrayList(); // create threads for (String name : collection) { final CallObject object = new CallObject(name); threads.add(object); } // start all Threads results = pool.invokeAll(threads, 3, TimeUnit.SECONDS); for (Future future : results) { try { // this method blocks until it receives the result, unless there is a // timeout set. final String rs = future.get(); if (future.isDone()) { // if future.isDone() = true, a timeout did not occur. // do something } else { // timeout // log it and do something break; } } catch (Exception e) { } } } catch (InterruptedException ex) { } 

是否确保我以future.get()的顺序接收结果,我创建新的CallObjects并将它们添加到我的ArrayList中? 我知道,文档说明如下: invokeAll(): returns a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list. If the operation did not time out, each task will have completed. If it did time out, some of these tasks will not have completed. invokeAll(): returns a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list. If the operation did not time out, each task will have completed. If it did time out, some of these tasks will not have completed. 但我想确保我理解正确….

谢谢你的回答! 🙂

这正是这段声明所说的:

返回表示任务的Futures列表,其顺序与迭代器为给定任务列表生成的顺序相同。

您将按照在Callable原始列表中插入项目的确切顺序获取Future

根据文档,您将以相同的顺序获得期货。

未来的对象只是该任务的参考。

 Future#get() is blocking call. 

对于前者

我们已经提交了4项任务。

任务1 – >完成

任务2 – >完成

任务3 – >超时

任务4 – >完成

根据我们的代码

 for (Future future : futures) { future.get(); } 

对于1和2秒的任务,它将立即返回。 我们将等待第三项任务完成。 即使第4个任务完成,迭代也在等待第三个任务。 一旦第三个任务完成或定时等待到期,那么只有迭代才会继续。