方式一:
public static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);
// 使用多线程并行查询
List<CompletableFuture<JSONObject>> futures = new ArrayList<>();
for (Double num : selectArr) {
CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
// 多线程下可能会导致 stickerSpellDTO 被其他线程修改
// 使每个线程都得到一个新的 StickerSpellDTO 对象,确保各个线程间不会对同一个对象进行修改
StickerSpellDTO dto = new StickerSpellDTO();
BeanUtils.copyProperties(stickerSpellDTO, dto);
dto.setNum(num);
return this.getOptimalFeeDetailByNum(dto, false, info);
}, EXECUTOR_SERVICE);
futures.add(future);
}
optimalFeeDetails = futures.stream()
.map(CompletableFuture::join)
.sorted(Comparator.comparing(jo -> jo.getDouble("num")))
.collect(Collectors.toList());
方式二:
public static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(10);
// 使用多线程并行查询
List<JSONObject> asyncOptimalFeeDetails = new ArrayList<>();
CountDownLatch countDownLatch = new CountDownLatch(selectArr.length);
for (Double num : selectArr) {
EXECUTOR_SERVICE.submit(() -> {
try {
// 多线程的情况下可能会导致 stickerSpellDTO 被其他线程修改
// 使每个线程都得到一个新的 StickerSpellDTO 对象,确保各个线程之间不会对同一个对象进行修改
StickerSpellDTO dto = new StickerSpellDTO();
BeanUtils.copyProperties(stickerSpellDTO, dto);
dto.setNum(num);
JSONObject optimalFeeDetailByNum = this.getOptimalFeeDetailByNum(dto, false, info);
asyncOptimalFeeDetails.add(optimalFeeDetailByNum);
} finally {
countDownLatch.countDown();
}
});
}
try {
// 当子线程全部执行完后,再继续执行主线程
countDownLatch.await();
} catch (InterruptedException ignored) {
}
optimalFeeDetails = asyncOptimalFeeDetails.stream()
.sorted(Comparator.comparing(jo -> jo.getDouble("num")))
.collect(Collectors.toList());