Java异步处理集合
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.14</version>
</dependency>
public class DemoList {
private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 100, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(512));
public static void main(String[] args){
List<Integer> dataList = new ArrayList<>();
for (int i = 1; i <= 100000; i++) {
dataList.add(i);
}
StopWatch stopWatch = new StopWatch();
stopWatch.start();
List<CompletableFuture> results = new ArrayList<>();
List<List<Integer>> partition = ListUtil.partition(dataList, 1000);
for (int i1 = 0; i1 < partition.size(); i1++) {
int finalI = i1;
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
printNum(partition.get(finalI));
return 1;
}, executor);
results.add(future);
}
CompletableFuture.allOf(results.toArray(results.toArray(new CompletableFuture[partition.size()]))).join();
stopWatch.stop();
executor.shutdown();
System.out.println("总用时"+stopWatch.getTotalTimeMillis()+"毫秒");
}
public static void printNum(List<Integer> list ){
for (int i = 0; i < list.size(); i++) {
System.out.println("++++"+list.get(i));
}
}
}