springboot创建线程池的方法

网上创建线程池的办法一搜一大堆,现在我把我使用的做一个总结记录

首先是线程池中的各项参数

我只用到了其中几项,在application.yml配置文件

threadpool:
  # 核心线程池数(根据自身电脑cpu核数*2+1)(但是考虑通用性,以及使用时的感受在此设置5)
  corePoolSize: 5
  #最大线程
  maxPoolSize: 10
  #队列容量(满了的时候,排队的长度)
  queueCapacity: 1000

如下是项目所引入的完整代码

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
@ConfigurationProperties(prefix = "threadpool")
@PropertySource(name = "application.yml", value = {"classpath:/application.yml"})
public class ExecutorConfig {
    @Value("${corePoolSize}")
    private int corePoolSize;

    @Value("${maxPoolSize}")
    private int maxPoolSize;

    @Value("${queueCapacity}")
    private int queueCapacity;

    @Bean(name = "taskExecutor")
    public Executor asynsServiceExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);

        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
}

如果当你的配置文件可以自动搜索到上述配置文件的内容,可以把注释中的下面代码去掉

@PropertySource(name = "application.yml", value = {"classpath:/application.yml"})

一般线程代码都是从controller层使用,下面是引入的代码,service层不动

	@Resource(name = "taskExecutor")
    private Executor taskExecutor;

		//控制层接入service层的入口
    	taskExecutor.execute(()->{
                try {
                    //service方法
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值