ThreadPoolExecutor 阻塞队列满了,如何保证任务不丢弃

当ThreadPoolExecutor 的任务阻塞队列满了,该怎么保证任务不丢失呢?

1.修改线程池的拒绝策略为ThreadPoolExecutor.CallerRunsPolicy 采用主线程来执行任务

        ExecutorService executorService = new ThreadPoolExecutor(3, 3, 6, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), new ThreadPoolExecutor.DiscardPolicy());

2.自定义拒绝策略,记录因队列满的请求参数,存储记录,可后续处理

        ExecutorService executorService = new ThreadPoolExecutor(3, 3, 6, TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), new MyRejectExecutionHander());
        for (int i = 0; i < 100; i++) {
            MyRunnable myRunnable = new MyRunnable();
            myRunnable.setName(i + "");
            executorService.execute(myRunnable);
        }
MyRejectExecutionHander 
public class MyRejectExecutionHander implements RejectedExecutionHandler {
    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
          MyRunnable myRunnable= (MyRunnable) r;
         // myRunnable.
        String name = myRunnable.getName();
        System.out.println("拒绝了一条数据"+name);

    }
}

 MyRunnable name 作为参数传递


public class MyRunnable implements Runnable {
    private String name;
    public void setName(String name)
    {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void run()
    {
        System.out.println("hello " + name);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值