线程池的使用
线程池基础
1、什么是线程池
用一句话来概述就是:线程池是指在初始化一个多线程应用程序过程中创建一个线程集合,然后再需要执行新的任务时重用这些线程而不是新建线程。
2、为什么使用线程池
使用线程池最大的原因就是可以根据系统的需求和硬件环境灵活的控制线程的数量,且可以对所有线程进行统一的管理和控制,从而提高系统的运行效率,降低系统的运行压力。
3、线程池有那些优势
降低资源消耗:线程和任务分离,提高线程重用性
控制线程并发数量,降低服务器压力,统一管理所有线程
提高系统响应速度。假如创建线程用的时间为T1,执行任务的时间为T2,销毁线程的时间为T3,那么使用线程池就免去了T1和T3的时间。
线程池的使用
例如:进入一个页面需要增加该页面阅读数字段的访问次数,则需要在缓存出该页面之前增加该阅读数字段的访问次数,所以在返回页面所需要数据之前,添加一个增加阅读次数的操作,这时便用到了线程池操作
步骤一、在文章业务层返回页面数据之前添加该操作
步骤二、添加一个ThreadService类用于添加阅读次数操作
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.he.blogapi.mapper.ArticleMapper;
import com.he.blogapi.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class ThreadService {
//期望次操作在线程池 执行 不会影响原有的主线程
@Async("taskExecutor") //#添加线程池操作
public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
int viewCounts = article.getViewCounts();
Article articleUpdate = new Article();
articleUpdate.setViewCounts(viewCounts + 1);
LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(Article::getId,article.getId());
//设置一个 为了在多线程的环境下 线程安全
queryWrapper.eq(Article::getViewCounts,viewCounts);
articleMapper.update(articleUpdate,queryWrapper);
try {
Thread.sleep(5000);
System.out.println("更新完成了。。。");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
步骤三、线程池ThreadPoolConfig类配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync //开启多线程
public class ThreadPoolConfig {
@Bean("taskExecutor")
public Executor asyncServiceExecutor(){
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;
}
}


浙公网安备 33010602011771号