1、在springboot启动类上添加@EnableAsync
@SpringBootApplication
@EnableConfigurationProperties
@EnableAsync
public class Main {
public static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
logger.info("Spring Boot Beginning ...");
SpringApplication.run(Main.class, args);
}
}
2、在需要异步开启线程执行方法上添加@Aysnc注解
@Async
public void threadMethod() {
log.info("********** hello world start **********");
try {
log.info("**********");
} catch (Exception e) {
log.error("hello java 异常");
}
}
3、可以配置@Async的线程配置
默认情况下核心线程数CorePoolSize为1,最大线程数是int的最大值,可以定义配置类来实现AsyncConfigurer 接口,自定义线程池的配置;
@Component
public class MyAsyncConfigurer implements AsyncConfigurer {
private static final Logger log = LoggerFactory.getLogger(MyAsyncConfigurer.class);
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
//设置核心线程数,默认为1
threadPool.setCorePoolSize(1);
// 当核心线程都在跑任务,还有多余的任务会存到此处。
threadPool.setQueueCapacity(100);
//最大线程数,默认为Integer.MAX_VALUE,如果queueCapacity存满了,还有任务就会启动更多的线程,直到线程数达到maxPoolSize。如果还有任务,则根据拒绝策略进行处理。
threadPool.setMaxPoolSize(1);
threadPool.setWaitForTasksToCompleteOnShutdown(true);
threadPool.setAwaitTerminationSeconds(60 * 15);
threadPool.setThreadNamePrefix("MyAsync-");
threadPool.initialize();
return threadPool;
}
}