如何在项目中使用线程池自定义拒绝策略

首先呢,我设计了一个图表在我的项目里面,为了方便展示,我只修改一个字段,线程池设置参数 (2,4,30, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(4),new RJ());
然后通过循环持续的进行增加任务,目的修改数据库的gentoal字段

拒绝策略:

public class RJ implements RejectedExecutionHandler {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

            RunT runT = (RunT) r;
            Chart chart = runT.getChart();
            chart.setGoal("拒绝");
            runT.getChartService().save(chart);

    }
}

任务:

package com.xxbi.springbootinit.Reject;
import com.xxbi.springbootinit.model.entity.Chart;
import com.xxbi.springbootinit.service.ChartService;


public class RunT implements  Runnable{
    private  final  Chart chart;
    private  final String goal;
    private final ChartService chartService;

    public Chart getChart() {
        return chart;
    }

    public String getGoal() {
        return goal;
    }

    public ChartService getChartService() {
        return chartService;
    }


    @Override
    public void run() {
        try {
            chart.setGoal(goal);
            chartService.save(chart);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public RunT(Chart chart,String goal,ChartService chartService){
        this.chart=chart;
        this.chartService=chartService;
        this.goal=goal;
    }
}

测试:


@SpringBootTest
public class M {
    @Resource
    private ChartService chartService;
    @Test
    public  void h() throws InterruptedException {
        ThreadPoolExecutor t=new ThreadPoolExecutor(2,4,30,
            TimeUnit.SECONDS, new ArrayBlockingQueue<>(4),new RJ());
        for(int i=0;i<10;i++){
            Chart chart =new Chart();
            String goal="goal"+i;
            System.out.println(goal);
            RunT runT=new RunT(chart,goal,chartService);
            t.execute(runT);
        }
        // 关闭线程池
        t.shutdown();
        // 等待所有任务完成
        if (!t.awaitTermination(1, TimeUnit.MINUTES)) {
            System.out.println("未终止");
            t.shutdownNow(); 
        }

    }

}

在这里插入图片描述

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值