springboot中使用线程池

本文详细介绍了一个Spring项目中线程池的具体配置方法,包括核心线程数、最大线程数、队列容量等参数设置,并展示了如何通过Bean的方式进行注入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;


@Configuration
public class DefaultThreadPoolConfig extends AsyncConfigurerSupport {

    /** Set the ThreadPoolExecutor's core pool size. */
    private int corePoolSize = 4;
    /** Set the ThreadPoolExecutor's maximum pool size. */
    private int maxPoolSize = 16;
    /** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */
    private int queueCapacity = 10;

    private String threadNamePrefix = "omsAsyncExecutor-";

    @Bean
    @Override
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(threadNamePrefix);

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
       //一定要等线程执行完成的时候才去关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
     //最大等待时间60s
        executor.setAwaitTerminationSeconds(60);
    //项目启动的时候就初始化线程池,避免到调用的时候才初始化
        executor.initialize();
        return executor;
    }

}

如果项目中其它地方有用到线程池,把ThreadPoolTaskExecutor注入即可。

转载于:https://my.oschina.net/hnqingping1255/blog/1862700

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值