Java ThreadPoolExecutor的拒绝策略CallerRunsPolicy

CallerRunsPolicy

  • execute 去执行新任务,也就是main线程去执行,这种策略会降低新任务提交速度,影响整体性能。

main方法

    public static void main(String[] args) {

        ExecutorService es = new ThreadPoolExecutor(2, 2, 0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(3), Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy());
        MyRunnable t1 = new MyRunnable("id:1");
        MyRunnable t2 = new MyRunnable("id:2");
        MyRunnable t3 = new MyRunnable("id:3");
        MyRunnable t4 = new MyRunnable("id:4");
        MyRunnable t5 = new MyRunnable("id:5");
        MyRunnable t6 = new MyRunnable("id:6");
        MyRunnable t7 = new MyRunnable("id:7");

        es.execute(t1);
        es.execute(t2);
        es.execute(t3);
        es.execute(t4);
        es.execute(t5);
        es.execute(t6);
        es.execute(t7);
    }

MyRunnable类

public class MyRunnable implements Runnable {
    String id;

    public MyRunnable(String id) {
        this.id = id;
    }

    @Override
    public void run() {
        System.out.println(id+"的线程名称:"+Thread.currentThread().getName());
    }
}

控制台输出

id:6的线程名称:main
id:2的线程名称:pool-1-thread-2
id:1的线程名称:pool-1-thread-1
id:3的线程名称:pool-1-thread-2
id:7的线程名称:main
id:5的线程名称:pool-1-thread-2
id:4的线程名称:pool-1-thread-1

总结

核心线程:2;
允许存在的工作线程最大数量:2
工作队列数量:5
id6,id7执行时队列、线程都已满,此时由主线程执行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值