Java:带有可调用对象的ExecutorService:invokeAll()和future.get()-结果顺序正确吗? [英] Java: ExecutorService with Callables: invokeAll() and future.get() - results in correct order?

查看:206
本文介绍了Java:带有可调用对象的ExecutorService:invokeAll()和future.get()-结果顺序正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Java中的ExecutorService通过invokeAll()调用线程.之后,用future.get()获得结果集.以创建线程的相同顺序接收结果非常重要.

Im using the ExecutorService in Java to invoke Threads with invokeAll(). After, I get the result set with future.get(). Its really important that I receive the results in the same order I created the threads.

这是一个代码段:

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.但是我想确保我理解正确....

Is it assured that I receive the results from future.get() in the same order I created new CallObjects and added them to my ArrayList? I know, Documentation says the following: 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. But I wanted to make sure I understood it correctly....

感谢您的回答! :-)

Thanks for answers! :-)

推荐答案

这正是声明的意思:

返回代表任务的期货列表,在同一列表中 迭代器针对给定任务列表产生的顺序.

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

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

You will get the Futures in the exact order in which you inserted the items in the original list of Callables.

这篇关于Java:带有可调用对象的ExecutorService:invokeAll()和future.get()-结果顺序正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆