分为三步
@SpringBootApplication
@EnableAsync
public class FacadeH5Application {
public static void main(String[] args) {
SpringApplication.run(FacadeH5Application.class, args);
}
}
@Async
public void m1() {
//do something
}
注意:导致 @Async 注解失效的几个原因
默认的线程池配置如下
# 核心线程数
spring.task.execution.pool.core-size=8
# 最大线程数
spring.task.execution.pool.max-size=16
# 空闲线程存活时间
spring.task.execution.pool.keep-alive=60s
# 是否允许核心线程超时
spring.task.execution.pool.allow-core-thread-timeout=true
# 线程队列数量
spring.task.execution.pool.queue-capacity=100
# 线程关闭等待
spring.task.execution.shutdown.await-termination=false
spring.task.execution.shutdown.await-termination-period=
# 线程名称前缀
spring.task.execution.thread-name-prefix=task-
@Configuration
public class ThreadPoolConfig {
@Bean
public TaskExecutor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//设置核心线程数
executor.setCorePoolSize(10);
//设置最大线程数
executor.setMaxPoolSize(20);
//设置队列容量
executor.setQueueCapacity(20);
//设置线程活跃时间
executor.setKeepAliveSeconds(30);
//设置线程名称前缀
executor.setThreadNamePrefix("sendSms-");
//设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
//设置线程池中任务的等待时间
executor.setAwaitTerminationSeconds(60);
return executor;
}
}
有时候,一个项目中如果配置了多个线程池,那需要在 @Bean后面加上线程池的名称
@Configuration
public class ThreadPoolConfig {
@Bean("ThreadPool1")
public TaskExecutor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
......
return executor;
}
@Bean("ThreadPool2")
public TaskExecutor taskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
......
return executor;
}
}
在使用 @Async注解时就需要指明具体使用的线程池,如下格式
@Async("ThreadPool1")
public void m1() {
//do something
}