我使用 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.
但我想确保我理解正确......
感谢您的回答!:-)