springboot项目如何引入线程池

1.在您的application.propertiesapplication.yml文件中,添加以下配置:

task:
  thread:
    pool:
      commonThreadPoolProperties:
        name: TaskExecutor-
        corePoolSize: 10
        maxPoolSize: 30
        keepAliveSeconds: 60
        queueCapacity: 8

2.设置线程配置类

@Data
@Component
@RefreshScope
@NoArgsConstructor
@AllArgsConstructor
@ConfigurationProperties(prefix = "task.thread.pool")
public class TaskThreadPoolConfig {
    TaskThreadPoolProperties commonThreadPoolProperties;
}

3.初始化线程池

@Configuration
@EnableAsync
@EnableScheduling
public class TaskExecutorConfig extends AsyncConfigurerSupport implements SchedulingConfigurer {
@Autowired
    protected TaskThreadPoolConfig taskThreadPoolConfig;
    @Autowired
    protected BeanFactory beanFactory;

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        return createExecutor(taskThreadPoolConfig.getCommonThreadPoolProperties(), beanFactory);
    }

    protected LazyTraceExecutor createExecutor(TaskThreadPoolProperties taskThreadPoolProperties, BeanFactory beanFactory) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //此方法返回可用处理器的虚拟机的最大数量; 不小于1
        //设置核心线程数
        executor.setCorePoolSize(taskThreadPoolProperties.getCorePoolSize());
        //设置最大线程数
        executor.setMaxPoolSize(taskThreadPoolProperties.getMaxPoolSize());
        //除核心线程外的线程存活时间
        executor.setKeepAliveSeconds(taskThreadPoolProperties.getKeepAliveSeconds());
        //如果传入值大于0,底层队列使用的是LinkedBlockingQueue,否则默认使用SynchronousQueue
        executor.setQueueCapacity(taskThreadPoolProperties.getQueueCapacity());
        //线程名称前缀
        executor.setThreadNamePrefix(taskThreadPoolProperties.getName());
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return new LazyTraceExecutor(this.beanFactory, executor);
    }
}

  • 11
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值