需求背景:
每次传入需要办卡的订单的集合,根据每个办卡订单进行办卡操作。
技术要点:
CompletableFuture:
@Autowired
private ThreadPoolTaskExecutor executor;
private ThreadPoolTaskExecutor executor;
方法:
List<CompletableFuture> futures = Collections.synchronizedList(new ArrayList<CompletableFuture>()); //创建线程集合
for (EtcCardApplyOrderRequestVo applyVo : etcCardApplyOrderRequestVoList) {
CompletableFuture<Result> future = CompletableFuture.supplyAsync(() -> applyOrder(applyOrderRequestVo),executor); //每个线程内都有个返回bigdecimal
futures.add(future);
futures.add(future);
}
//创建集合任务
CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allOf.join(); //等待执行结束
CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allOf.join(); //等待执行结束
//支付金额
amount = BigDecimal.ZERO;
for (CompletableFuture future : futures) {
if (future.isDone()){
try {
BigDecimal decimal = (BigDecimal) future.get();
amount = amount.add(decimal);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
amount = BigDecimal.ZERO;
for (CompletableFuture future : futures) {
if (future.isDone()){
try {
BigDecimal decimal = (BigDecimal) future.get();
amount = amount.add(decimal);
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
executor.shutdown();
}