结论:
1、线程池队列容量满了后,迅速扩容至maxPoolSize
2、队列满后,再进来任务,则主线程执行任务
3、任务执行完后,等待(keepAliveSeconds),主线程数然后恢复至corePoolSize
1、线程池初始化代码
@Bean
public ThreadPoolTaskExecutor getCareRightsExecutor() {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(40);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("care-right-");
executor.setQueueCapacity(965);
// 等待所有任务结果候再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
// 定义拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化线程池, 初始化 core 线程
executor.initialize();
return executor;
}
2、测试代码
@Resource
private ThreadPoolTaskExecutor getCareRightsExecutor;
@Test
void testThread() throws InterruptedException {
final Logger logP = LoggerFactory.getLogger(this.getClass());
for (int i = 0; i < 10000; i++) {
getCareRightsExecutor.execute(() -> {
try {
logP.info("队列长度:" + getCareRightsExecutor.getQueueSize());
Thread.sleep(RandomUtil.randomLong(1100, 2000));
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
});
}
//Thread.sleep(100000000);
}