版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzx_2011/article/details/79775052
问题
最近在用线程池写代码跑任务时抛了这个java.util.concurrent.RejectedExecutionException
异常,于是就查 了下自己的代码,原因是线程池调用shutdown()
后,又执行了新任务。在shutdown()执行前,老的任务会继续处理而不允许在提交新的任务。
注:分析和解决可以直接看参考资料中的两篇文章十分详细
原因
产生该异常一般有两个原因:
1.线程池调用shutdown()
后,又执行了新任务。
2.当线程池的排队策略为有界队列,而提交的任务超过了有界队列的长度时,就会抛该异常。所以排队策略可以不用有界队列,但注意任务太多无界队列可能内存溢出。
示例
这里只列出我遇到的第一个原因产生的异常。
public static void test(){
ExecutorService executorService = new ThreadPoolExecutor(5, 10,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
for(int j = 0; j < 5; j++){
List<Integer> list = Lists.newArrayList();
for(int i = 0; i < 5000; i++){
list.add(i);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
for(Integer integer : list){
executorService.execute(new Runnable() {
@Override
public void run() {
try {
System.out.println(integer);
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
}
});
}
//不能写在这里会抛异常
//executorService.shutdown();
}
//应该写在最后这里
executorService.shutdown();
}
参考资料
java.util.concurrent.RejectedExecutionException – How to solve RejectedExecutionException
java.util.concurrent.RejectedExecutionException