/**
* @auther fanxuebo
* @desc 线程池配置和初始化
* @Company
* @create 2018/12/29 8:23
*/
@Configuration
public class MyExecutorPool {
@Autowired
private ThreadPoolProperties threadPoolProperties;
@Bean(name = "myAsyncThread")
public ThreadPoolTaskExecutor myTaskAsyncPool() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());//表示线程池核心线程,正常情况下开启的线程数量。
executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());//当核心线程都在跑任务,还有多余的任务会存到此处。
executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());//如果queueCapacity存满了,还有任务就会启动更多的线程,直到线程数达到maxPoolSize。如果还有任务,则根据拒绝策略进行处理。
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//该策略是又调用任务的线程执行。
executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());//非核心线程的超时时长,超长后会被回收。
executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());
executor.initialize();//初始化线程池。
return executor;
}
}
/**
* @auther fanxuebo
* @desc 配置线程池参数读取配置文件
* @Company
* @create 2018/12/29 8:27
*/
@ConfigurationProperties("executor")
@Component
public class ThreadPoolProperties {
private Integer corePoolSize;
private Integer maxPoolSize;
private Integer queueCapacity;
private Integer keepAliveSeconds;
private String threadNamePrefix;
public Integer getCorePoolSize() {
return corePoolSize;
}
public void setCorePoolSize(Integer corePoolSize) {
this.corePoolSize = corePoolSize;
}
public Integer getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(Integer maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public Integer getQueueCapacity() {
return queueCapacity;
}
public void setQueueCapacity(Integer queueCapacity) {
this.queueCapacity = queueCapacity;
}
public Integer getKeepAliveSeconds() {
return keepAliveSeconds;
}
public void setKeepAliveSeconds(Integer keepAliveSeconds) {
this.keepAliveSeconds = keepAliveSeconds;
}
public String getThreadNamePrefix() {
return threadNamePrefix;
}
public void setThreadNamePrefix(String threadNamePrefix) {
this.threadNamePrefix = threadNamePrefix;
}
}
配置文件:
executor:
corePoolSize: 5
maxPoolSize: 10
queueCapacity: 20
keepAliveSeconds: 60
threadNamePrefix: XCExecutor-
在springboot启动类加@EnableAsync注解,然后在需要多线程执行的方法上加注解@Async(value = "myAsyncThread")即可。