执行多线程时报错如下
java.util.concurrent.RejectedExecutionException: Task com.kmvc.hbtowergather.config.ScheduleTask$$Lambda$836/1805505087@3f6e7bee rejected from java.util.concurrent.ThreadPoolExecutor@6a154334[Running, pool size = 50, active threads = 50, queued tasks = 1024, completed tasks = 20]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at com.kmvc.hbtowergather.config.ScheduleTask.handleChannelLive(ScheduleTask.java:483)
at com.kmvc.hbtowergather.config.ScheduleTask.readFile(ScheduleTask.java:291)
at com.kmvc.hbtowergather.config.ScheduleTask.hbTowerGather(ScheduleTask.java:142)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:84)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset$$$capture(FutureTask.java:308)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
使用 java.util.concurrent.ThreadPoolExecutor.execute(Runnable command) 方法提交任务时,当线程池中正在使用的线程数达到了设置的最大的值(50),而且队列已(1000),就会报错。
解决方法:
方法一、增加判断即可:executor.getActiveCount()<50时才执行execute方法
if (((ThreadPoolExecutor) executorService).getActiveCount() < 50) {
executorService.execute(() -> {
insertHDPT_CHANNEL_LIVE(sublist);
});
}
方法二:将存放待处理任务的队列数量设置大一点
private final static Integer QUEUE_SIZE = 1024*10;
ExecutorService executorService = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(QUEUE_SIZE), nameThreadFactory,
new ThreadPoolExecutor.AbortPolicy());