spring boot的线程池配置
/**
* 线程池配置
*
*/
@EnableAsync
@Configuration
public class AsyncConfig implements AsyncConfigurer {
//初始化@Async需要的线程池
@Override
public Executor getAsyncExecutor() {
/**满足aop的前提下,用@Async注解来做异步执行**/
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5); //核心线程数
executor.setMaxPoolSize(10); //最大线程数
executor.setQueueCapacity(100); //队列大小
executor.setKeepAliveSeconds(300); //线程最大空闲时间
executor.setThreadNamePrefix("async-executor-"); //指定用于新创建的线程名称的前缀。
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //拒绝策略(一共四种)
executor.initialize();
return executor;
}
// 异常处理器
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
/**
* 普通线程池
* @return
*/
@Bean("normalTheadPool")
public Executor getTheadPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5); //核心线程数
executor.setMaxPoolSize(10); //最大线程数
executor.setQueueCapacity(50); //队列大小
executor.setKeepAliveSeconds(300); //线程最大空闲时间
executor.setThreadNamePrefix("normal-thead-pool-"); //指定用于新创建的线程名称的前缀。
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //拒绝策略
executor.initialize();
return executor;
}
}
//使用方式
@Async
@Override
public void judgeEnd() {
startJudge();
}
private void startJudge() {
system.out.println("异步判断")
}
通过统一线程池的配置,利用注入的方式来使用线程池对象。需要注意的是使用@Async注解,必须得满足spring的aop机制。