1,定义ThreadPoolTaskExecutor
@Bean
public ThreadPoolTaskExecutor terminalActivityDetectionTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setMaxPoolSize(terminalJobActivityDetectionProperties.getMaxPoolSize());
threadPoolTaskExecutor.setCorePoolSize(terminalJobActivityDetectionProperties.getCorePoolSize());
threadPoolTaskExecutor.setQueueCapacity(terminalJobActivityDetectionProperties.getQueueCapacity());
threadPoolTaskExecutor.setThreadNamePrefix(terminalJobActivityDetectionProperties.getThreadNamePrefix());
threadPoolTaskExecutor.setKeepAliveSeconds(terminalJobActivityDetectionProperties.getKeepAliveSeconds());
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
threadPoolTaskExecutor.setTaskDecorator(MagicalRunnableWrapper::new);
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
此处,bean name 为 terminalActivityDetectionTaskExecutor
2,在具体的实现类中注入Bean
private final ThreadPoolTaskExecutor terminalActivityDetectionTaskExecutor;
public TerminalActivityDetectionServiceImpl(ThreadPoolTaskExecutor terminalActivityDetectionTaskExecutor) {
this.terminalActivityDetectionTaskExecutor = terminalActivityDetectionTaskExecutor;
}
3,使用@Async注解,编辑value的值为自定义的线程池bean名称。
此处@Async注解中value的值为 为 terminalActivityDetectionTaskExecutor(之前定义的bean名称)
@Async(value = "terminalActivityDetectionTaskExecutor")
public void asyncExecute(Object executeData) {
//此处编写具体的任务执行代码
}