第一步:定义多线程类,继承Thred类
public class GetCommodityThread extends Thread {
private final static Logger LOGGER = LoggerFactory.getLogger(GetCommodityThread.class);
private BasicDataFeignClientService basicDataFeignClientService;
private CountDownLatch countDownLatch;
private GoodsIdsReq goodsIdsReq;
private List<Map<String, GoodsVO>> mapList;
public GetCommodityThread(BasicDataFeignClientService basicDataFeignClientService, CountDownLatch countDownLatch,
GoodsIdsReq goodsIdsReq, List<Map<String, GoodsVO>> mapList) {
this.basicDataFeignClientService = basicDataFeignClientService;
this.countDownLatch = countDownLatch;
this.goodsIdsReq = goodsIdsReq;
this.mapList = mapList;
}
@Override
public void run() {
this.doGet();
countDownLatch.countDown();
LOGGER.info("还剩余线程数:" + countDownLatch.getCount());
}
private void doGet() {
ResultData<Map<String, GoodsVO>> commodityMapByIds = basicDataFeignClientService.getCommodityMapByIds(goodsIdsReq);
if (commodityMapByIds != null) {
Map<String, GoodsVO> data = commodityMapByIds.getData();
mapList.add(data);
}
}
}
第二步:在service层具体使用线程类
private Map<String, GoodsVO> getGoodsMap(List<AfterSalesDTO> afterSalesList) {
List<String> goodIds = new ArrayList<>();
for (AfterSalesDTO afterSalesDTO : afterSalesList) {
List<AfterSalesItemDTO> itemDTOList = afterSalesDTO.getItems();
if (CollectionUtils.isNotEmpty(itemDTOList)) {
for (AfterSalesItemDTO afterSalesItemDTO : itemDTOList) {
goodIds.add(afterSalesItemDTO.getItemId());
}
}
}
goodIds = goodIds.stream().distinct().collect(Collectors.toList());
List<Map<String, GoodsVO>> listMap = new ArrayList<>();
listMap = Collections.synchronizedList(listMap);
Integer countRow = goodIds.size();
Integer times = 0;
Integer perCount = 10000;
if (countRow % perCount == 0) {
times = countRow / perCount;
} else {
times = countRow / perCount + 1;
}
CountDownLatch countDownTimes = new CountDownLatch(times);
List<String> innerList = new ArrayList<>();
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.initialize();
executor.setCorePoolSize(3);
for (int i = 1; i <= goodIds.size(); i++) {
innerList.add(goodIds.get(i - 1));
if (i % perCount == 0) {
GoodsIdsReq goodsIdsReq = new GoodsIdsReq();
goodsIdsReq.setCommodityIds(innerList);
executor.execute(new GetCommodityThread(basicDataFeignClientService, countDownTimes, goodsIdsReq, listMap));
innerList = new ArrayList<>();
continue;
}
if (i % perCount != 0 && i == countRow) {
GoodsIdsReq goodsIdsReq = new GoodsIdsReq();
goodsIdsReq.setCommodityIds(innerList);
executor.execute(new GetCommodityThread(basicDataFeignClientService, countDownTimes, goodsIdsReq, listMap));
}
}
try {
countDownTimes.await();
} catch (InterruptedException e) {
logger.info("InterruptedException occurs");
}
Map<String, GoodsVO> collect = listMap.stream()
.map(Map::entrySet)
.flatMap(Set::stream)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return collect;
}
里面加入些具体的参数,可以根据实际情况来写