1. 线程池配置
@Configuration
public class TaskExecutorConfig implements AsyncConfigurer {
@Value("${async.core.pool.size:10}") //核心线程数
private Integer corePoolSize;
@Value("${async.max.pool.size:40}") //最大线程数
private Integer maxPoolSize;
@Value("${async.queue.capacity:2000}") //任务队列
private Integer queueCapacity;
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(corePoolSize);
taskExecutor.setMaxPoolSize(maxPoolSize);
taskExecutor.setQueueCapacity(queueCapacity);
taskExecutor.setThreadNamePrefix("async-service-"); //线程池的前缀名称
taskExecutor.initialize();
return taskExecutor;
}
(1)ThreadPoolTaskExecutor实际上就是通过initialize()方法实现对ThreadPoolExecutor的包装。
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);