第一步:在springboot主類中加入線程池注解
@SpringBootApplication
@EnableSwagger2
@EnableScheduling
//開啟線程池注解
@EnableAsync
public class MongodbApplication {
public static void main(String[] args) {
SpringApplication.run(MongodbApplication.class, args);
}
}
第二步:編寫線程池配置類
@Configuration
public class ThreadAsyncConfig implements AsyncConfigurer {
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
//設定核心線程數
threadPool.setCorePoolSize(10);
//設定最大線程數
threadPool.setMaxPoolSize(100);
//線程池所使用的緩沖隊列
threadPool.setQueueCapacity(10);
//等待任務在關機時完成--表明等待所有線程執行完
threadPool.setWaitForTasksToCompleteOnShutdown(true);
// 等待時間 (預設為0,此時立即停止),并沒等待xx秒後強制停止
threadPool.setAwaitTerminationSeconds(60);
// 線程名稱字首
threadPool.setThreadNamePrefix("MyAsync-");
// 初始化線程
threadPool.initialize();
return threadPool;
}
}
第三步:在需要用到多線程的業務層添加@Async注解
/**
* 儲存使用者
* @param user
*/
//添加異步操作調用線程池線程
@Async
public void save(UserEntity user){
System.out.println("線程名稱:"+Thread.currentThread().getName());
userDao.save(user);
}
注意:在同一時間如果通路量大于最大線程數,将拒絕之後的通路,并且報 RejectedExecutionException錯誤。