一、 为什么要使用线程池?
1. 降低创建和销毁线程的资源消耗, 提高响应速度
2.方便统一管理线程,在配置文件里配置@Value获取就行
二、线程池分类
1.FixThreadPool 定长线程池 (推荐)
2.CachedThreadPool 缓存线程池,会自动扩容
3.ScheduledThreadPool 定时线程池
4.SingleThreadPool 单线程的线程池
辅助配置文件工具依赖,使用它在配置文件时会有提示,字段名称会根据驼峰命名规则使用横杠切割字段,可有可无,推荐使用
<!--配置属性提示工具 我的版本是springboot-parent维护 所以没有版本号-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
目录结构如下
1.配置文件映射类
package com.atguigu.gulimall.product.config.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* User: ldj
* Date: 2022/9/17
* Time: 16:35
* Description:
* 1.@Component或 @Configuration 两个注解都是将配置类立即注入容器,就可以直接使用。
* 2.如果在A类需要时,再注入就使用注解@EnableConfigurationProperties(ThreadPoolConfigProperties.class)。
* 3.ignoreInvalidFields = true 如果配置写的非法参数会获取null,但有默认值会使用默认值。
*/
@Data
//@Component或 @Configuration
@ConfigurationProperties(prefix = "thread.pool.executor.config", ignoreInvalidFields = true)
public class ThreadPoolConfigProperties {
private Integer corePoolSize = 20;
private Integer maximumPoolSize = 200;
private Long keepAliveTime = 10L;
private Integer blockQueueSize = 100000;
}
2.注入Bean到容器
package com.atguigu.gulimall.product.config;
import com.atguigu.gulimall.product.config.properties.ThreadPoolConfigProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* User: ldj
* Date: 2022/9/17
* Time: 16:12
* Description: 线程池配置
*/
@Configuration
@EnableConfigurationProperties(ThreadPoolConfigProperties.class)
public class MyThreadPoolConfig {
@Bean
@ConditionalOnMissingBean(ThreadPoolExecutor.class)
public ThreadPoolExecutor threadPoolExecutor(ThreadPoolConfigProperties properties) {
return new ThreadPoolExecutor(properties.getCorePoolSize(),
properties.getMaximumPoolSize(),
properties.getKeepAliveTime(),
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(properties.getBlockQueueSize()),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
}
}
3.配置文件 application.properties
#2.线程池配置
thread.pool.executor.config.core-pool-size=20
thread.pool.executor.config.maximum-pool-size=200
thread.pool.executor.config.keep-alive-time=10
thread.pool.executor.config.block-queue-size=100000
三、线程池的拒绝策略
ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常。 【默认】
ThreadPoolExecutor.DiscardPolicy:直接丢弃任务,但是不会抛出异常
ThreadPoolExecutor.DiscardOldestPolicy:将最早进入队列的任务删除,之后再尝试加入队列的任务被拒绝
ThreadPoolExecutor.CallerRunsPolicy:如果任务添加线程池失败,那么主线程自己执行该任务