Java 线程池中的四种拒绝策略

public class MyThreadPool2 {
    /**
     * 线程池的四种拒绝策略
     */
    public static void main(String[] args) {
        new MyThreadPool2().req(new MyThreadPool2().four());
    }

    /**
     * 第一种拒绝策略:抛异常
     * Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.dawn.one.MyThreadPool2$$Lambda$1/764977973@3feba861 rejected from java.util.concurrent.ThreadPoolExecutor@5b480cf9[Running, pool size = 5, active threads = 0, queued tasks = 0, completed tasks = 12]
     * 	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
     * 	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
     * 	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
     * 	at com.dawn.one.MyThreadPool2.req(MyThreadPool2.java:36)
     * 	at com.dawn.one.MyThreadPool2.main(MyThreadPool2.java:14)
     */
    public RejectedExecutionHandler one(){
        return new ThreadPoolExecutor.AbortPolicy();
    }

    /**
     * 第二种拒绝策略:无异常,哪里来,那里去
     */
    public RejectedExecutionHandler two(){
        return new ThreadPoolExecutor.CallerRunsPolicy();
    }

    /**
     * 第三种拒绝策略:无异常,优先抛弃最老的任务,并且执行当前任务
     */
    public RejectedExecutionHandler three(){
        return new ThreadPoolExecutor.DiscardOldestPolicy();
    }

    /**
     * 第四种拒绝策略:无异常,直接抛弃需要等待的代码
     */
    public RejectedExecutionHandler four(){
        return new ThreadPoolExecutor.DiscardPolicy();
    }
    /**
     * 业务代码
     * @param handler 四种拒绝方式
     */
    public void req(RejectedExecutionHandler handler){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                5,
                2l,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(2),
                Executors.defaultThreadFactory(),
                handler
        );
        for (int i = 0; i < 200; i++) {
            int num = i;
            threadPoolExecutor.execute(()->{
                System.out.println(Thread.currentThread().getName()+"\t 顾客真正处理业务"+num);
            });
        }
        threadPoolExecutor.shutdown();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值