簡體   English   中英

Java:帶有Callables的ExecutorService:invokeAll()和future.get()-結果順序正確嗎?

[英]Java: ExecutorService with Callables: invokeAll() and future.get() - results in correct order?

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

感謝您的回答! :-)

這正是聲明的意思:

返回代表任務的Future列表,其順序與迭代器為給定任務列表生成的順序相同。

您將按照將項目插入到Callable原始列表中的確切順序來獲取Future

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

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

Future#get() is blocking call.

對於前

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

任務1->已完成

任務2->已完成

任務3->超時

任務4->已完成

根據我們的代碼

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

對於1&2秒的任務,它將立即返回。 我們將等待第三項任務完成。 即使第四個任務完成,迭代也會在第三個任務中等待。 一旦第三項任務完成或定時等待在該時間到期,則僅迭代將繼續。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM