Java:带有 Callables 的 ExecutorService:invokeAll() 和 future.get() - 结果顺序正确吗?

标签 java multithreading invoke executorservice callable

我在 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)
{
}

是否确保我从 future.get() 接收结果的顺序与我创建新 CallObjects 并将它们添加到我的 ArrayList 的顺序相同?我知道,文档说明如下: invokeAll():返回表示任务的 Futures 列表,其顺序与迭代器为给定任务列表生成的顺序相同。如果操作没有超时,则每个任务都已完成。如果确实超时,其中一些任务将不会完成。 但我想确保我理解正确....

谢谢解答! :-)

最佳答案

这正是这段声明所说的:

returns a list of Futures representing the tasks, in the same sequential order as produced by the iterator for the given task list.

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

关于Java:带有 Callables 的 ExecutorService:invokeAll() 和 future.get() - 结果顺序正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9632960/

相关文章:

c# - 使用 Type 变量调用正确的泛型方法,带 out 和 ref

c# - 使用两个不同变量类型的参数调用?

c# - Control.Invoke 展开外部异常并传播内部异常

java - 在使用枚举之前检查有效的枚举值

java - Netty 4中服务器端和客户端高低写水印选项的区别

c# - 每次在 C# 中接收到新连接时,如何创建一个新线程?

java - 像 read() 这样的 I/O 方法如何在 Java 中将线程置于阻塞状态?

java - 数字日期格式

java - EntityManager 和 DAO 有什么区别?

c# - 另一个后台 worker