目录
1.设置线程池的参数
#定时任务线程池参数
task:
pool:
corePoolSize: 5 # 核心线程数
maxPoolSize: 20 #设置最大线程数
keepAliveSeconds: 300 #设置线程活跃时间,单位秒
queueCapacity: 100 #设置队列容量
2.接收线程池参数
/**
* 获取yml文件中的参数
*/
@Data
@ConfigurationProperties(prefix = "task.pool" )
public class TaskThreadPoolConfig {
private Integer corePoolSize;
private Integer maxPoolSize;
private Integer keepAliveSeconds;
private Integer queueCapacity;
}
3.使用注解标记
使用@EnableConfiggurationProperties(具体的线程池参数类)标记
@MapperScan("com.xz.stock.mapper")
@SpringBootApplication
@EnableConfigurationProperties({TaskThreadPoolConfig.class})
public class JobApplication {
public static void main(String[] args) {
SpringApplication.run(JobApplication.class, args);
}
}
4.配置bean
/**
* 定义线程池的配置类
*/
@Configuration
public class TaskExecutePoolConfig {
@Autowired
private TaskThreadPoolConfig threadInfo;
/**
* 定义线程池bean
*
* @return
*/
@Bean(name = "threadPoolTaskExecutor",destroyMethod = "shutdown")
public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
//设置核心线程数
taskExecutor.setCorePoolSize(threadInfo.getCorePoolSize());
//设置最大线程数
taskExecutor.setMaxPoolSize(threadInfo.getMaxPoolSize());
//置线程活跃时间,单位秒
taskExecutor.setKeepAliveSeconds(threadInfo.getKeepAliveSeconds());
//设置队列容量
taskExecutor.setQueueCapacity(threadInfo.getQueueCapacity());
//设置拒绝策略
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//将参数初始化
taskExecutor.initialize();
return taskExecutor;
}
}
5.使用
class MyTest{
//注入线程池
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
public void getThread() {
long startTime = System.currentTimeMillis();
//引入线程池
threadPoolTaskExecutor.execute(()->{
//执行的业务
});
long endTime = System.currentTimeMillis();
log.info("执行时间:{}ms",endTime-startTime);
}
}