使用场景:在处理List存储的入参时,使用开启多线程处理,并使处理结果与入参顺序一致(即与List顺序一致)
解决思路:
1、将List转为请求Map,通过Map记录下标和入参,以下标为Key,入参为value;
2、将结果存入新建结果Map,Key为请求Map的Key(原List下标),value为处理结果值;
3、使用CountDownLatch,保证在进行重新排序时结果全部执行完毕;
4、新建结果List,通过对结果Map中的Key值进行重新排序。
public Result getFeeDesByTemplate(List list, String applyType) {
Map<Integer, MultiPoolTradeResultDTO> tradeResultMap = getSaleGroupFeeDesByFeeTrade(list, applyType);
Map<Integer, JSONArray> resultMap = new HashMap<>();
// 线程资源共享
RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(), true);
CountDownLatch countDownLatch = new CountDownLatch(tradeResultMap.size());
for (Map.Entry<Integer, MultiPoolTradeResultDTO> entry : tradeResultMap.entrySet()) {
// 异步处理
new Thread(() -> {
try {
JSONArray jsonArray = new JSONArray();
MultiPoolTradeResultDTO tradeResultDTO = entry.getValue();
JSONObject tmpResult = queryRealSubjectFee(tradeResultDTO, applyType);
if (!ObjectUtils.isEmpty(tmpResult)) {
jsonArray.add(tmpResult);
}
resultMap.put(entry.getKey(), jsonArray);
} catch (Exception e) {
log.error(e.getMessage());
throw new BusinessException(e.getMessage());
} finally {
countDownLatch.countDown();
}
}).start();
}
// 等待全部结束
try {
countDownLatch.await();
} catch (Exception e) {
log.error(e.getMessage());
throw new BusinessException(e.getMessage());
}
List resultList = new ArrayList();
for (int i = 0; i < resultMap.size(); i++) {
resultList.add(i, resultMap.get(i));
}
return Result.ofSuccess(resultList);
}