1.第一步需要在主方法上加@EnableAsync注解
2.第二步创建一个配置类,如下:
@Configuration
@EnableAsync
public class AsyncTaskConfig implements AsyncConfigurer{
@Override
@Bean
public Excutor getAsyncExecutor(){
ThreadPoolTaskExecutor threadPool =new ThreadPoolTaskExcutor();
threadPool.setCorePoolSize(10); //线程池 核心线程数
threadPool.setMaxPoolSize(20); //线程池 最大线程数
threadPool.setQueueCapacity(1000); //队列大小
threadPool.setWaitForTasksToCompleteOnShutdowm(true);
threadPool.setAwaitTerminationSeconds(60);
threadPool.setThreadNamePrefix("yys"); //线程名前缀
threadPool.initialize();
return threadPool;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler(){
return null;
}
然后在service层方法上加上@Async注解即可以开启多线程,这里注意线程方法和调用线程方法的方法不能在同一个类中。
具体测试demo请自行测试。
}