3

我使用 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<String> 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)
{
}

是否可以确保我以与创建新 CallObjects 并将它们添加到我的 ArrayList 的顺序相同的顺序从 future.get() 接收结果?我知道,文档说如下: 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.但我想确保我理解正确......

感谢您的回答!:-)

4

2 回答 2

8

这正是声明中所说的:

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

您将Future按照在 s 的原始列表中插入项目的确切顺序获得Callables。

于 2012-03-09T15:40:14.743 回答
1

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

Future 对象只是任务的引用。

Future#get() is blocking call.

例如

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

任务 1 - > 已完成

任务 2 --> 已完成

任务 3 --> 超时

任务 4 --> 已完成

根据我们的代码

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

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

于 2014-08-15T18:22:49.137 回答