无参
List<HealthGroupDataDTO> groupDataDTOS = new ArrayList<>();
List<List<Long>> schoolSplitIds = DataUtil.splitData(schoolIds, 4000);
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (List<Long> schoolSplitId : schoolSplitIds) {
futures.add(CompletableFuture.runAsync(() -> {
try {
groupDataDTOS.addAll(healthStatisMapper.selectSchoolTemperList(schoolSplitId, queryTime));
} catch (Exception e) {
e.printStackTrace();
}
}));
}
//等待全部完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
有参
ExecutorService executor = new ThreadPoolExecutor(
8, 100, 5,
TimeUnit.MINUTES,
new ArrayBlockingQueue<>(10000)
);
List<HealthGroupDataDTO> groupDataDTOS = new ArrayList<>();
List<CompletableFuture<HealthGroupDataDTO>> fList = new ArrayList<>();
groupDataDTOS.forEach(groupData->{
CompletableFuture<HealthGroupDataDTO> f = CompletableFuture.supplyAsync(
//执行耗时较长的业务代码,这里模拟一下
()->{
groupData.setTime("");
return groupData;
},
executor
);
fList.add(f);
});
// 阻塞,等待所有任务执行完成
CompletableFuture<Void> all= CompletableFuture.allOf(fList.toArray(new CompletableFuture[0]));
//因为allOf没有返回值,所以需要通过thenApply回调函数获取结果
CompletableFuture<List<HealthGroupDataDTO>> allUser=all.thenApply(v-> fList.stream().map(a-> {
try {
return a.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList()));
groupDataDTOS=allUser.get();
多线程-使用线程池
异步执行汇总
//先定义一个线程池
private final ThreadPoolExecutor poolExecutor= ExecutorBuilder.create().setCorePoolSize(10).setMaxPoolSize(100).build();
public void importExcel() throws Exception {
//这个是需要去遍历处理的数据
List<OWazyLocationVO> excelDataList = .........;
//这个是最终汇总的 集合数据
List<WayzLocationResult> dataList = new ArrayList<>();
//Hutool线程工具,异步执行结束后汇总需要用到,若不需要汇总,仅多线程执行,这个countDownLatch 相关可以直接删掉
CountDownLatch countDownLatch = ThreadUtil.newCountDownLatch(excelDataList.size());
this.poolExecutor.execute(() -> {
for (OWazyLocationVO pos : excelDataList ) {
//调用其他服务或查询返回的结果,汇总到dataList 中
WayzLocationResult wayzLocationResult = forestWayzLocationService.trackPoint(pos);
dataList.add(wayzLocationResult );
countDownLatch.countDown();
}
});
//汇总,等待多线程结束
countDownLatch.await();
log.info("dataList查询多线程处理结束:" + dataList.size());
}