1、配置文件中线程池的参数
//corePoolSize 线程池核心线程大小
test.corePoolSize=20
//maxPoolSize 线程池最大线程数量
test.maxPoolSize=40
//keepAliveTime 空闲线程存活时间
test.keepAliveSeconds=300
//queueCapacity 缓存队列容量
test.queueCapacity=50
2、线程配置config类
@Configuration //声明配置类
@EnableAsync //标记
public class ExcutorConfig {
@Value("${test.corePoolSize}")
private int corePoolSize;
@Value("${test.maxPoolSize}")
private int maxPoolSize;
@Value("${test.keepAliveSeconds}")
private int keepAliveSeconds;
@Value("${test.queueCapacity}")
private int queueCapacity;
@Bean("taskExecutor")//调用线程时的线程名字
public Executor asyncExcelServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setKeepAliveSeconds(keepAliveSeconds);
//对拒绝task的处理策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
3、启动类上增加启动线程注解
@EnableAsync
@EnableConfigurationProperties({ExcutorConfig .class} ) // 开启配置属性支持
4、接下来是调用线程执行任务
@Async("taskExecutor")
public Future<> doTask(int i) throws Exception{
logger.info("执行线程任务!!");
return new AsyncResult<>()
}
5、调用异步执行,返回一个Future对象,.get()拿到实际获取到的对象。