1.在您的application.properties
或application.yml
文件中,添加以下配置:
task:
thread:
pool:
commonThreadPoolProperties:
name: TaskExecutor-
corePoolSize: 10
maxPoolSize: 30
keepAliveSeconds: 60
queueCapacity: 8
2.设置线程配置类
@Data
@Component
@RefreshScope
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "task.thread.pool")
public class TaskThreadPoolConfig {
TaskThreadPoolProperties commonThreadPoolProperties;
}
3.初始化线程池
@Configuration
@EnableAsync
@EnableScheduling
public class TaskExecutorConfig extends AsyncConfigurerSupport implements SchedulingConfigurer {
@Autowired
protected TaskThreadPoolConfig taskThreadPoolConfig;
@Autowired
protected BeanFactory beanFactory;
@Bean("taskExecutor")
public Executor taskExecutor() {
return createExecutor(taskThreadPoolConfig.getCommonThreadPoolProperties(), beanFactory);
}
protected LazyTraceExecutor createExecutor(TaskThreadPoolProperties taskThreadPoolProperties, BeanFactory beanFactory) {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//此方法返回可用处理器的虚拟机的最大数量; 不小于1
//设置核心线程数
executor.setCorePoolSize(taskThreadPoolProperties.getCorePoolSize());
//设置最大线程数
executor.setMaxPoolSize(taskThreadPoolProperties.getMaxPoolSize());
//除核心线程外的线程存活时间
executor.setKeepAliveSeconds(taskThreadPoolProperties.getKeepAliveSeconds());
//如果传入值大于0,底层队列使用的是LinkedBlockingQueue,否则默认使用SynchronousQueue
executor.setQueueCapacity(taskThreadPoolProperties.getQueueCapacity());
//线程名称前缀
executor.setThreadNamePrefix(taskThreadPoolProperties.getName());
//设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return new LazyTraceExecutor(this.beanFactory, executor);
}
}