在真实项目开发场景中正确使用线程池

在真实项目开发场景中正确使用线程池

这是在项目中正确使用自定义线程池的代码,至于为什么不使用Executors创建线程池,请参考我的上一篇文章:阿里开发手册为什么强制要求使用自定义线程池?

//全局线程池
​
@Configuration
public class ThreadPoolConfig{
​
/**
* 自定义线程池配置
**/
    @Bean
    public TaskExecutor taskExecutor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(10);
        //设置最大线程数
        executor.setMaxPoolSize(20);
        //设置阻塞队列容量
        executor.setQueueCapacity(10);
        //设置线程存活时间(s)
        executor.setKeepAliveSeconds(30);
        //设置默认线程名称
        executor.setThreadNamePrefix("my-task-executor-");
        //设置拒绝策略(当资源不足时,哪个线程提交哪个线程运行)
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //等待所有任务结束后关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

在需要用到线程池时把taskExecutor这个Bean引入使用即可。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值