springboot线程池快速使用
1.编写配置类
@EnableAsync 注解开启spring的线程池功能
注册一个线程池到ioc中
@Configuration
@EnableAsync //开启线程池
public class ThreadPoolConfig {
@Bean("taskExecutor") //开启多线程
public Executor asyncServiceExecuter(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//设置核心线程数
executor.setCorePoolSize(5);
//设置最大线程数
executor.setMaxPoolSize(20);
//配置队列大小
executor.setQueueCapacity(Integer.MAX_VALUE);
//设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
//设置默认线程名称
executor.setThreadNamePrefix("码神之路博客项目");
//等待所有任务结束后在关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
//执行初始化
executor.initialize();
return executor;
}
}
2.使用线程池
在方法上添加注解
@Async(“taskExecutor”)
该方法就会交给线程池处理
@Async("taskExecutor")
public void updateViewCounts(Article article) {
int viewCounts = article.getViewCounts();
article.setViewCounts(viewCounts + 1);
LambdaUpdateWrapper<Article> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
lambdaUpdateWrapper.eq(Article::getId,article.getId());
//设置一个 为了多线程下线程安全
lambdaUpdateWrapper.eq(Article::getViewCounts,viewCounts);
articleService.update(article, lambdaUpdateWrapper);
}