提交的任务被线程池拒绝了。
原因:显示的调用了 shutdown(),下次再添加,就被池拒绝了。
错误代码示例:
public class RetailerResultAllocationExecutor implements Runnable {
private static Integer threadSize = 4;
private static ExecutorService executorService = Executors.newFixedThreadPool(threadSize);
private List<RetailerCalculationResultAllocationVo> resultVos;
public RetailerResultAllocationExecutor(List<RetailerCalculationResultAllocationVo> resultVos) {
this.resultVos = resultVos;
}
public static ExecutorService getExecutorService() {
if(null == executorService){
executorService = Executors.newFixedThreadPool(threadSize);
}
return executorService;
}
@Override
public void run() {
if (CollectionUtils.isEmpty(resultVos)) {
return;
}
int size = resultVos.size();
List<List<RetailerCalculationResultAllocationVo>> list = new ArrayList<>();
List<Integer> itemCount = new ArrayList<>();
itemCount.add(0);
for (int i = 1; i <= size; i++) {
if (i % 100 == 0 || i == size) {
itemCount.add(i);
}
}
for (int i = 0; i < itemCount.size() - 1; i++) {
List<RetailerCalculationResultAllocationVo> itemList = resultVos.subList(itemCount.get(i), itemCount.get(i + 1));
list.add(itemList);
}
IRetailerCalculationResultInfoService retailerCalculationResultInfoService = SpringUtil.getBean(IRetailerCalculationResultInfoService.class);
try {
CountDownLatch latch = new CountDownLatch(list.size());
for (List<RetailerCalculationResultAllocationVo> resultAllocationVos : list) {
getExecutorService().submit(new RetailerResultAllocationThread(retailerCalculationResultInfoService, resultAllocationVos, latch));
}
// 等待 更新线程更新完再落地数据
latch.await();
} catch (InterruptedException e) {
log.error(e.getMessage());
}finally {
executorService.shutdown();
}
log.info("Thread end!");
}
}
线程池executorService定义为static了,程序第一次调用该线程没有问题,但是下次再调用的话,就会报出 Method threw ‘java.util.concurrent.RejectedExecutionException’ exception. 该错误。
原因:程序中显示的 executorService.shutdown(); 但 executorService 为static, 下次调用 getExecutorService()该方法时,不会再重新创建线程池了。故,报出该错误。