线程池执行器一般有两种构建方式 1. 自定义线程池config类并实现AsyncConfigurer接口 该种方式需要重写public Executor getAsyncExecutor() {} , 否则会使用默认的线程池 优势是可以自动注入 @Async 2. 自定义线程池config类 @Async("customExecutor") 需要指定名称 @Configuration 被spring管理 可作为实例被业务需求引用
@Configuration
@EnableAsync
public class CustomAsyncThreadConfig {
@Bean(name = "customExecutor")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//有些状态在 ThreadPoolTaskExecutor 可能获取不到, 可以先获取 ThreadPoolExecutor
//线程池在运行过程中已完成的任务数
// executor.getThreadPoolExecutor().getCompletedTaskCount();
// 核心线程数:创建线程池初始化的线程数
executor.setCorePoolSize(20);
// 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(200);
// 缓冲队列:用来缓冲执行任务的队列
executor.setQueueCapacity(25);
// 允许线程的空闲时间200秒:当超过了核心线程之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(200);
// 线程池名的前缀:方便定位处理任务所在的线程池
executor.setThreadNamePrefix("customAsyncThread-");
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
//调用execute方法的上层线程去执行拒绝(一般是主线程)
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//解决调用时报线程池未初始化的异常
executor.initialize();
return executor;
}
}
@EnableAsync 开启异步线程调用 @Bean(name = "customExecutor") 线程池执行器当作一个bean被spring管理
线程执行器定义完成后,一般有三种使用方式
//方式1 // @Autowired // private CustomAsyncThreadConfig customAsyncThreadConfig; //方式2 // Executor executor = SpringUtils.getBean("customExecutor"); //方式3 @Async("customExecutor")
方式1一般用于业务模块中,也就是常见的@Service
方式2一般用于自定义线程,比如某项业务需要单独进行线程处理
方式3一般作用于方法 ,如果实现了AsyncConfigurer接口,可不带执行器的名称