我在 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/