2012-03-09 24 views
2

使用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.但我想確保我正確理解它....

感謝您的答案! :-)

+1

是的,它是,否則你怎麼能確定哪個結果是哪個Callable的結果? – 2012-03-09 11:11:23

+0

這將是可能的 - 但不必要的複雜。 :-)它有時很容易誤解文檔,所以我只想確定...謝謝! – nano7 2012-03-09 12:00:27

回答

4

這正是這塊的聲明是說:

返回表示任務的Future列表,在同 順序由迭代器給定的任務列表製作。

您將得到Future S IN您在其中的Callable送原裝插入列表中的項目的確切順序。

1

根據文件,您將獲得相同順序的期貨。

未來的對象只是任務的參考。

Future#get() is blocking call. 

對於離

我們已經提交了4個任務。

任務1 - >已完成

任務2 - >已完成

任務3 - >超時

任務4 - >已完成

根據我們的代碼

for (Future future : futures) { 
    future.get(); } 

For 1 & 2秒任務它將立即返回年。我們將等待第三項任務將完成。即使第四項任務完成,迭代也在第三項任務中等待。一旦第三項任務完成或定時等待到期,那麼只有迭代纔會繼續。

相關問題