文章目录
自定义线程池有2种方法:
第一种:是自定义线程池,使用时指定线程池名称,执行异步任务。
第二种:重写spring默认线程池,然后使用自己重写后的线程池,执行异步任务。
一、自定义线程池
1. yml配置
# 线程池配置参数
task:
pool:
corePoolSize: 10 # 设置核心线程数
maxPoolSize: 20 # 设置最大线程数
keepAliveTime: 300 # 设置空闲线程存活时间(秒)
queueCapacity: 100 # 设置队列容量
threadNamePrefix: "-signpolicy-asynnotify-" # 设置线程名称前缀
awaitTerminationSeconds: 60 # 设置线程池等待终止时间(秒)
spring:
main:
allow-bean-definition-overriding: true
2. 线程池配置属性类
package com..config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* 线程配置属性类
*
* @Author
* @Date 2022-04-05 17:20
**/
@Data
@ConfigurationProperties(prefix = "task.pool")
public class TaskThreadPoolConfig {
private int corePoolSize;
private int maxPoolSize;
private int keepAliveSeconds;
private int queueCapacity;
private int awaitTerminationSeconds;
private String threadNamePrefix;
}
3. 开启异步线程支持
在启动类上/开启异步线程支持+开启配置属性支持
package com.;
import com..config.TaskThreadPoolConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync//开启异步线程支持
@EnableConfigurationProperties({TaskThreadPoolConfig.class})//开启配置属性支持
@SpringBootApplication
public class AsyncThreadApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncThreadApplication.class, args);
}
}
4. 创建自定义线程池配置类
package com..config;
import org.springframework.beans.factory.annotation.Autowired;
import org.spri