springboot 初始化线程池_springboot自定义线程池

本文档详细介绍了如何在 SpringBoot 中自定义并初始化线程池。通过 `MyExecutorPool` 类配置 `ThreadPoolTaskExecutor`,设置核心线程数、最大线程数、队列容量、超时时间等参数,并使用 `ThreadPoolProperties` 从配置文件读取相关属性。同时,介绍了如何配置拒绝策略以及如何在启动类启用异步注解,确保多线程任务的正确执行。
摘要由CSDN通过智能技术生成

/**

* @auther fanxuebo

* @desc 线程池配置和初始化

* @Company

* @create 2018/12/29 8:23

*/

@Configuration

public class MyExecutorPool {

@Autowired

private ThreadPoolProperties threadPoolProperties;

@Bean(name = "myAsyncThread")

public ThreadPoolTaskExecutor myTaskAsyncPool() {

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

executor.setCorePoolSize(threadPoolProperties.getCorePoolSize());//表示线程池核心线程,正常情况下开启的线程数量。

executor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());//当核心线程都在跑任务,还有多余的任务会存到此处。

executor.setQueueCapacity(threadPoolProperties.getQueueCapacity());//如果queueCapacity存满了,还有任务就会启动更多的线程,直到线程数达到maxPoolSize。如果还有任务,则根据拒绝策略进行处理。

executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//该策略是又调用任务的线程执行。

executor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());//非核心线程的超时时长,超长后会被回收。

executor.setThreadNamePrefix(threadPoolProperties.getThreadNamePrefix());

executor.initialize();//初始化线程池。

return executor;

}

}

/**

* @auther fanxuebo

* @desc 配置线程池参数读取配置文件

* @Company

* @create 2018/12/29 8:27

*/

@ConfigurationProperties("executor")

@Component

public class ThreadPoolProperties {

private Integer corePoolSize;

private Integer maxPoolSize;

private Integer queueCapacity;

private Integer keepAliveSeconds;

private String threadNamePrefix;

public Integer getCorePoolSize() {

return corePoolSize;

}

public void setCorePoolSize(Integer corePoolSize) {

this.corePoolSize = corePoolSize;

}

public Integer getMaxPoolSize() {

return maxPoolSize;

}

public void setMaxPoolSize(Integer maxPoolSize) {

this.maxPoolSize = maxPoolSize;

}

public Integer getQueueCapacity() {

return queueCapacity;

}

public void setQueueCapacity(Integer queueCapacity) {

this.queueCapacity = queueCapacity;

}

public Integer getKeepAliveSeconds() {

return keepAliveSeconds;

}

public void setKeepAliveSeconds(Integer keepAliveSeconds) {

this.keepAliveSeconds = keepAliveSeconds;

}

public String getThreadNamePrefix() {

return threadNamePrefix;

}

public void setThreadNamePrefix(String threadNamePrefix) {

this.threadNamePrefix = threadNamePrefix;

}

}

配置文件:

executor:

corePoolSize: 5

maxPoolSize: 10

queueCapacity: 20

keepAliveSeconds: 60

threadNamePrefix: XCExecutor-

在springboot启动类加@EnableAsync注解,然后在需要多线程执行的方法上加注解@Async(value = "myAsyncThread")即可。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值