2011-08-05 35 views
1

我有請求列表,我需要在線程中發送它們,並在線程完成時收集所有響應。我怎麼知道所有的步驟都完成了?ExecutionService。所有線程完成後如何獲得結果?

List<Task<Response>> tasks = new ArrayList<Task<Response>>(); 
for (Request request : requestList) { 
     tasks.add(executor.runTask(new RequestCaller(request))); // runTask is my method witch will run threads 
} 
for (int i = 0; i < tasks.size; i++) { 
    result.add(tasks.get(i).get); // here i want to collect results, but i need to run this loop only when all threads will finish 
} 

回答

2

一種方法是使用一個CountDownLatch,通過鎖對象給每個線程,讓每個線程調用countDown()自己鎖釦對象時完成,然後通過任何你想要的鎖調用await()的線程等待暫停直到所有線程完成。

// note: code not tested 
List<Task<Response>> tasks = new ArrayList<Task<Response>>(); 
CountDownLatch latch = new CountDownLatch(tasks.size()); 
for (Request request : requestList) { 
    // pass latch into RequestCaller 
    tasks.add(executor.runTask(new RequestCaller(request, latch))); // runTask is my method which will run threads 
} 
// in RequestCaller, call countDown() on the latch when finished. 

latch.await(); // wait for all threads to call countDown() on their latches. 
for (int i = 0; i < tasks.size(); i++) { 
    result.add(tasks.get(i).get); // here i want to collect results, but i need to run this loop only when all threads will finish 
} 
1

檢出ExecutorService.invokeAll,其中包含可調用列表,並行執行並在全部完成時返回(或可選地在超時後返回)