我有一種情況,我的代碼需要對串列中的每個“基金”進行大量計算。
我可以按順序進行,而且效果很好,但是需要很多時間。對于 1 個基金,大約需要 13-15 分鐘。我必須為 50 多個基金運行它,這需要大量時間。
代碼片段是這樣的:
List<Map<String, Object>> fundsList = getTheListOfFunds()
Iterator<Map<String, Object>> itr = fundsList.listIterator();
List<Map<String, Object>> expectedDataList = new ArrayList<>();
while (itr.hasNext()) {
Map<String, Object> finalData = doCalc(parameter1, parameter2, parameter3);
expectedDataList.add(finalData);
}
我對多執行緒很陌生。有人可以幫我重構代碼,以便計算(doCalc)可以在多個執行緒而不是單個執行緒中完成嗎?
uj5u.com熱心網友回復:
您可以使用該Executors.newFixedThreadPool(int)方法獲取 ExecutorService 來提交任務。
您提交到執行緒池的每個任務都將回傳一個Future,您可以在以后維護一個串列并檢索回傳的值。
這是一個例子:
// Create a new fixed thread pool with a predefined number of threads.
final ExecutorService service = Executors.newFixedThreadPool(10);
// Create a list of Future objects to retrieve later.
List<Future<Map<String, Object>>> futures = new ArrayList<>();
// Loop through your list and for each iteration, submit your task
// to the Executor service, and add the result to your Future list.
for (Map<String, Object> fund: fundsList) {
futures.add(service.submit(() -> doCalc(/* parameters */)));
}
// Loop through the Future list and call the .get() method to
// retrieve the computed value.
for (Future<Map<String, Object>> future: futures) {
try {
final Map<String, Object> finalData = future.get();
expectedDataList.add(finalData);
} catch (InterruptedException | ExecutionException e) {
// log or throw error
}
}
uj5u.com熱心網友回復:
謝謝大家的回答和評論。特別感謝 @blacktide 和 @federOnline 讓我們朝著正確的方向前進。我和 Brajesh 一起作業,這是我們寫的,如有任何問題,請糾正我們。
public class MyThreadTest {
public static void main(String[] args) {
final ExecutorService service = Executors.newFixedThreadPool(3);
// Create a list of Future objects to retrieve later.
List<Future<Integer>> futures = new ArrayList<>();
// Loop through your list and for each iteration, submit your task
// to the Executor service, and add the result to your Future list.
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] b = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(int i=0; i<a.length; i ) {
int finalI = i;
futures.add(service.submit(() -> add(a[finalI], b[finalI])));
}
// Loop through the Future list and call the .get() method to
// retrieve the computed value.
List<Integer> list = new ArrayList<>();
for (Future<Integer> future: futures) {
try {
int finalData = future.get();
if(future.isDone()) {
list.add(finalData);
}
} catch (InterruptedException | ExecutionException e) {
// log or throw error
}
}
System.out.println(list.size());
service.shutdown();
}
public static int add(int a, int b) {
System.out.println(Thread.currentThread().getName());
return a b;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513745.html
標籤:爪哇多线程列表地图
