我想用多個執行緒執行一些 java 邏輯,并且該方法回傳一個串列。所以最后我希望所有執行緒結果都變成單個串列?是否可以使用 Java ExecutorService 或多執行緒?或任何其他 Java 框架?
uj5u.com熱心網友回復:
有不同的方法可以做到這一點,這是我的建議:
創建一個串列Callable(在檔案中查看更多資訊):
List<Callable<Object>> callables = new ArrayList<>();
將您的任務添加到此串列中:
callables.add(() -> {
// do something
});
然后通過將它們傳遞給 的invokeAll()方法ExecutorService并接收 的串列來呼叫這些可呼叫物件Future<Object>。例如:
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<Object>> results = executor.invokeAll(callables);
然后,您可以通過從result串列中通過索引呼叫獲取它們來獲取每個執行緒結果- 與您將它們傳遞到 Callable 串列的順序相同。
因此,要獲得傳遞給 Callable 串列的第一個執行緒的結果,只需執行以下操作:
CastedResult result = (CastedResult) results.get(0).get();
最后,您可以根據需要將所有結果收集在一個串列中。
此外,這是一篇關于如何使用的有用文章ExecutorService(并記住在完成使用后關閉 Executor,如此處所述)。
uj5u.com熱心網友回復:
我想用多個執行緒執行一些 java 邏輯,并且該方法回傳一個串列。所以最后我希望所有執行緒結果都變成單個串列?
我可以想到幾種方法來做到這一點。一種方法是將 a 傳遞給BlockingQueue所有作業。然后他們每個人都可以將結果添加到同一個集合中。
任何其他解決方案可能意味著每個作業回傳一個,List并且當您加入作業時,您將每個作業串列添加到最終串列中。
ExecutorService threadPool = Executors.newFixedThreadPool(NUM_THREADS);
List<Future<List<Foo>>> futures = new ArrayList<>();
for (int i = 0; i < NUM_JOBS; i ) {
// add another job to the thread-pool and record the future
futures.add(threadPool.submit(new Callable<List<Foo>>() {
@Override
public List<Foo> call() throws Exception {
// create the list here
return list;
}
});
}
// shutdown the pool but the jobs continue running
threadPool.shutdown();
List<Foo> finalList = new ArrayList<Foo>();
for (Future<List<Foo>> future : futures) {
// calling get waits for each job to finish in order
// we add all of the results from the job list into the final list
finalList.addAll(future.get());
}
這會按順序等待每個作業。如果您想在結果完成時將結果添加到串列中,那么您可以使用ExecutorCompletionService。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/382688.html
上一篇:在python中,.start()命令是否阻塞執行緒開始完成所需的時間?
下一篇:從執行緒中洗掉重復的行
