Java多執行緒之執行多個任務並處理所有結果
阿新 • • 發佈:2019-01-07
執行器框架給我們提供了一個方法,讓我們可以傳送給執行器一個任務列表,並等待任務列表中的所有任務執行完畢。然後它將返回一個與任務列表對應的Future列表。
package com.primer.demo.util;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
@Slf4j
public class ThreadPool {
private static ExecutorService executorService = new ThreadPoolExecutor(100, 500, 1, TimeUnit.SECONDS, new LinkedBlockingDeque());
public static <T> List<T> addTask(List<Callable<T>> tasks) {
List<Future<T>> futureList = null;
List<T> results = null;
try {
futureList = executorService.invokeAll(tasks);
results = new ArrayList<>();
for (Future<T> future : futureList) {
results.add(future.get());
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return results;
}
}
建立多個任務並顯示結果:
package com .primer.demo.service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import com.primer.demo.util.ThreadPool;
@RunWith(SpringRunner.class)
@SpringBootTest
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Rollback(false)
public class Demo2ServiceTest {
@Test
public void test(){
List<Callable<String>> callables = new ArrayList<>();
for(int i=0;i<10;i++){
callables.add(()-> Math.random()+"");
}
List<String> res = ThreadPool.addTask(callables);
System.out.println("**********************");
for(String str : res){
System.out.println(str);
}
}
}