/**
* @author: zcs
* @Title: TaskPoolConfig
* @Description: 线程池配置
* @date: 2023/10/11 17:52
*/
@Component
public class TaskPoolConfig {
@Bean(name = "threadPoolTaskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//核心线程池大小,设置为当前系统可用的处理器数量+1
taskExecutor.setCorePoolSize(Runtime.getRuntime().availableProcessors() + 1);
//最大线程池大小,设置为当前系统可用的处理器数量*2
taskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
//队列最大容量
taskExecutor.setQueueCapacity(1000);
//存活时间
taskExecutor.setKeepAliveSeconds(60);
//设置线程名前缀
taskExecutor.setThreadNamePrefix("taskExecutor--");
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
//拒绝策略
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.setAwaitTerminationSeconds(60);
return taskExecutor;
}
}
使用:
1.首先注入线程池对象
@Autowired
@Qualifier("threadPoolTaskExecutor")
private Executor threadPoolTaskExecutor;
2.方法里面使用线程池
threadPoolTaskExecutor.execute(() -> {
//代码逻辑
});