线程池需要返回值
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 10, 500, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(20), Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
public List<AdapterItemVO> getItemSkuList(List<ItemSkuQueryRO> queryList) {
List<AdapterItemVO> itemSkuList = new ArrayList<>();
if(CollectionUtils.isEmpty(queryList)){
return new ArrayList<>();
}
List<List<ItemSkuQueryRO>> partition = Lists.partition(queryList, 10);
CountDownLatch countDownLatch = new CountDownLatch(partition.size());
for (List<ItemSkuQueryRO> itemSkuQueryROList: partition) {
try{
Future<List<AdapterItemVO>> submit = threadPool.submit(new FutureTaskCallable(itemSkuQueryROList, null,countDownLatch));
itemSkuList.addAll(submit.get());
}catch (Exception e){
log.info("多线程获取商品sku信息列表失败",e);
}
}
try{
countDownLatch.await();
}catch (Exception e){
log.info("多线程获取商品sku信息列表失败",e);
}
return itemSkuList;
}
private class FutureTaskCallable implements Callable<List<AdapterItemVO>> {
private List<ItemSkuQueryRO> queryList;
private Long storeId;
private CountDownLatch countDownLatch;
FutureTaskCallable(List<ItemSkuQueryRO> queryList, Long storeId, CountDownLatch countDownLatch){
this.queryList = queryList;
this.storeId = storeId;
this.countDownLatch = countDownLatch;
}
@Override
public List<AdapterItemVO> call(){
List<AdapterItemVO> itemSkuList = new ArrayList<>();
try{
itemSkuList = getItemSkuList(queryList, storeId);
}catch (Exception e){
log.info("多线程获取商品sku信息列表失败",e);
}finally {
countDownLatch.countDown();
}
return itemSkuList;
}
}
线程池不需要返回值
private void preheatDataByAcid(List<Long> allItemCategoryIdList, Long acid) {
CountDownLatch countDownLatch = new CountDownLatch(acids.size());
for (Long acid : acids) {
try {
threadPool.execute(new Task(allItemCategoryIdList,acid,countDownLatch));
} catch (Exception e) {
LOGGER.info("预热车辆安装位置信息失败"+acid ,e);
}
}
countDownLatch.await();
}
class Task implements Runnable {
private List<Long> allItemCategoryIdList;
private Long acid;
private CountDownLatch countDownLatch;
public Task(List<Long> allItemCategoryIdList, Long acid, CountDownLatch countDownLatch) {
this.allItemCategoryIdList = allItemCategoryIdList;
this.acid = acid;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
preheatDataByAcid(allItemCategoryIdList, acid);
} catch (Exception e) {
LOGGER.info(acid + "预热车辆预热车辆安装位置信息失败" + e);
} finally {
countDownLatch.countDown();
}
}
}