// 分成 10 个线程并行处理数据 int threadNum = 10; int dataSizePerThread = awardIds.size() / threadNum; List<CompletableFuture<List<TCaAwardInfo>>> futures = new ArrayList<>(); for (int i = 0; i < threadNum; i++) { int startIndex = i * dataSizePerThread; int endIndex = (i == threadNum - 1) ? awardIds.size() : (i + 1) * dataSizePerThread; List<Long> subList = awardIds.subList(startIndex, endIndex); CompletableFuture<List<TCaAwardInfo>> future = CompletableFuture.supplyAsync(() -> { List<TCaAwardInfo> result = new ArrayList<>(); List<TCaAwardInfo> tCaAwardInfos = awardApiService.queryActivationCode(subList); result.addAll(tCaAwardInfos); return result; }, taskExecutor); futures.add(future); } // 等待所有线程执行完毕 CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); allFutures.join(); // 合并结果 List<TCaAwardInfo> activationCodeList = futures.stream() .flatMap(future -> future.join().stream()) .collect(Collectors.toList()); 优化一下这个代码
时间: 2024-02-28 17:54:20 浏览: 85
这段代码的并行处理数据的逻辑已经很好了,可以考虑在结果合并的时候进行优化。可以使用`CompletableFuture.join()`方法替代`CompletableFuture.join().stream()`,这样可以避免创建Stream对象,提高代码执行效率。同时,可以考虑使用`addAll()`方法替代`flatMap()`和`collect(Collectors.toList())`方法,从而避免创建Stream对象和List对象,提高代码执行效率。代码改进后如下:
```
int threadNum = 10;
int dataSizePerThread = awardIds.size() / threadNum;
List<CompletableFuture<List<TCaAwardInfo>>> futures = new ArrayList<>();
for (int i = 0; i < threadNum; i++) {
int startIndex = i * dataSizePerThread;
int endIndex = (i == threadNum - 1) ? awardIds.size() : (i + 1) * dataSizePerThread;
List<Long> subList = awardIds.subList(startIndex, endIndex);
CompletableFuture<List<TCaAwardInfo>> future = CompletableFuture.supplyAsync(() -> {
List<TCaAwardInfo> result = new ArrayList<>();
List<TCaAwardInfo> tCaAwardInfos = awardApiService.queryActivationCode(subList);
result.addAll(tCaAwardInfos);
return result;
}, taskExecutor);
futures.add(future);
}
List<TCaAwardInfo> activationCodeList = new ArrayList<>();
for (CompletableFuture<List<TCaAwardInfo>> future : futures) {
activationCodeList.addAll(future.join());
}
```
阅读全文