java-多线程并发,CompletableFuture
//无返回值
@Override public void execCreateYmDetDataSubTask(YmDetCreateWorkerDto ymDetCreateWorkerDto){ List<Long> sendIdList = ymDetCreateWorkerDto.getSendIdList(); List<List<Long>> subLists = Lists.partition(sendIdList, 10); List<CompletableFuture<Void>> completableFutures = new ArrayList<>(); for(List<Long> subList : subLists){ CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{ createYmDetData(subList,ymDetCreateWorkerDto.getBillYm(),ymDetCreateWorkerDto.getVerifyTaskId()); },pool); completableFutures.add(completableFuture); } //本次子任务执行完毕 CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join(); List<ChildTaskStatusDto> childTaskStatusDtoList = new ArrayList<>(); //TODO 子任务数据组装 try { batchService.updateChildTaskStatusBatch(ymDetCreateWorkerDto.getBusiBatchId(),childTaskStatusDtoList); } catch (WorkerException e) { throw new BaseException(e); } }
//有返回值
private List queryBatchByIds(List<Long> ids, Integer current, Integer size) { List<BillBatchAdjTmpFileDTO> list = new ArrayList<>(); if (CollectionUtils.isEmpty(ids)) { return list; } //截取当前需要处理的id数 List<Long> subList = BillUtils.getSubIdList(ids, current, size); //获取所有数据 List<BillAdjManDetTmp> billAdjManDetTmps = super.listByIds(subList); List<CompletableFuture<BillBatchAdjTmpFileDTO>> futures = new ArrayList<>(); for (BillAdjManDetTmp manDet : billAdjManDetTmps) { CompletableFuture<BillBatchAdjTmpFileDTO> billAdjSendErrFileDtoCompletableFuture = CompletableFuture.supplyAsync(() -> { return getBillAdjSendErrFileDto(manDet); },pool); futures.add(billAdjSendErrFileDtoCompletableFuture); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); futures.forEach(n->list.add(n.join())); return list; }