线程池(3)Executors.newCachedThreadPool

例子:

ExecutorService es = Executors.newCachedThreadPool();
        try {
            for (int i = 0; i < 20; i++) {
                Runnable syncRunnable = new Runnable() {
                    @Override
                    public void run() {
                        log.info(Thread.currentThread().getName());
                        try {
                            Thread.sleep(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                };
                es.execute(syncRunnable);
            }
        } finally {
            es.shutdown();
        }

运行结果:

            10:21:04.610 pool-1-thread-13
            10:21:04.612 pool-1-thread-3
            10:21:04.612 pool-1-thread-7
            10:21:04.612 pool-1-thread-2
            10:21:04.610 pool-1-thread-14
            10:21:04.612 pool-1-thread-6
            10:21:04.611 pool-1-thread-8
            10:21:04.611 pool-1-thread-11
            10:21:04.611 pool-1-thread-4
            10:21:04.610 pool-1-thread-1
            10:21:04.611 pool-1-thread-20
            10:21:04.611 pool-1-thread-12
            10:21:04.610 pool-1-thread-16
            10:21:04.611 pool-1-thread-5
            10:21:04.611 pool-1-thread-9
            10:21:04.610 pool-1-thread-17
            10:21:04.610 pool-1-thread-18
            10:21:04.610 pool-1-thread-10
            10:21:04.611 pool-1-thread-15
            10:21:04.611 pool-1-thread-19

调用的调用的ThreadPoolExecutor:

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }

corePoolSize=0,maximumPoolSize=Integer.MAX_VALUE

keepAliveTime=60秒

allowCoreThreadTimeout=false(默认)

因此,

  • 核心线程数为0
  • 每来一个任务,先查看缓冲池中是否有可用线程(没超过60秒的),如果有,则用;没有,则就创建一个新线程
  • 因为核心线程数为0,池中的线程当达到60秒时,会超时关闭,直到核心线程数=0

 

转载于:https://www.cnblogs.com/yaoyuan2/p/9606504.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值