ava*_*lon 5 java multithreading java-8 threadpoolexecutor
我使用ThreadPoolExecutor 如下:
ThreadPoolExecutor pool = new ThreadPoolExecutor(cores, 50, 30L,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
Run Code Online (Sandbox Code Playgroud)
并且:
pool.execute(()->{
//code goes here
if(some condition){
return;
}
//code goes here
})
Run Code Online (Sandbox Code Playgroud)
当启用带有return语句的块时,所有这些任务都会卡在TPE中.TPE说它已经完全加载并且总是抛出RejectedExecutionException异常
我不明白为什么会这样.例如,如果您有一个大小为10的池,并且您有100个任务,其中10个将匹配if section,您将不接受第101个任务,所有下一个任务将被拒绝.为什么?
您没有正确配置ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue)
Run Code Online (Sandbox Code Playgroud)
使用给定的初始参数和默认线程工厂以及拒绝的执行处理程序创建新的ThreadPoolExecutor.使用Executors工厂方法之一而不是这个通用构造函数可能更方便.
参数:
corePoolSize - 除非设置了allowCoreThreadTimeOut,否则即使它们处于空闲状态,也要保留在池中的线程数
maximumPoolSize - 池中允许的最大线程数
keepAliveTime - 当线程数大于核心数时,这是多余空闲线程在终止之前等待新任务的最长时间.
unit - keepAliveTime参数的时间单位
workQueue - 在执行任务之前用于保存任务的队列.此队列将仅保存execute方法提交的Runnable任务.
我从未见过workQueue尺寸(10)小于maximumPoolSize (50)的TPE .使用当前配置,由于队列大小为10(此时的队列大小),第11个工作人员任务将被拒绝
增加你的workQueue尺寸摆脱RejectedExecutionException.50个线程可以轻松处理1000多个小型工作任务.根据您的要求配置此队列大小,并使用合理的值.