基于springboot配置线程池

1、新增配置类

@Configuration
public class ThreadPoolConfig {

    @Value("${thread.pool.corePoolSize}")
    private int corePoolSize;
    @Value("${thread.pool.maximumPoolSize}")
    private int maximumPoolSize;

    @Bean(name = "myThreadPool")
    public ThreadPoolExecutor myThreadPool() {
        return new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                60l,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new MyRejectPolicy()                            //自定义拒绝策略
//                new ThreadPoolExecutor.AbortPolicy()          // 终止策略抛出异常
//                new ThreadPoolExecutor.DiscardPolicy()        // 抛弃策略无异常
//                new ThreadPoolExecutor.DiscardOldestPolicy()  // 丢掉最早未处理的任务
//                new ThreadPoolExecutor.CallerRunsPolicy()     // 交由主线程执行
        );
    }
}

2、自定义拒绝策略

public class MyRejectPolicy implements RejectedExecutionHandler {
    //1、实现 ejectedExecutionHandler 接口
    //2、重写 rejectedExecution 方法
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

        try {

            // 核心改造点,由blockingqueue的offer改成put阻塞方法
            e.getQueue().put(r);
        } catch (InterruptedException exception) {
            exception.printStackTrace();
        }
    }
}

3、yml 文件属性配置

thread:
    pool:
        corePoolSize: 3
        maximumPoolSize: 5

4、测试类测试

@SpringBootTest
class OfficeAutoSysApplicationTests {

    @Autowired
    @Qualifier("myThreadPool")
    ThreadPoolExecutor threadPoolExecutor;

    @Test
    void test_1() {

        for (int i = 1; i < 100; i++) {
            int task = i;
            threadPoolExecutor.execute(() -> {
                System.out.println("线程:" + Thread.currentThread().getName() + "正在执行任务" + task);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}

4、输出结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值