使用Java中的ExecutorService調用invokeAll()
的線程。之後,我得到結果集future.get()
。以我創建線程的相同順序收到結果非常重要。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.
但我想確保我正確理解它....
感謝您的答案! :-)
是的,它是,否則你怎麼能確定哪個結果是哪個Callable的結果? – 2012-03-09 11:11:23
這將是可能的 - 但不必要的複雜。 :-)它有時很容易誤解文檔,所以我只想確定...謝謝! – nano7 2012-03-09 12:00:27