zoukankan      html  css  js  c++  java
  • 线程池(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
  • 相关阅读:
    POJ 2112 Optimal Milking (Dinic + 二分)
    [1444] The Waterfall Flow
    [1443] Weiqi
    POJ 3750 小孩报数问题 (约瑟夫问题)
    POJ 1386 Play on Words
    支持Delphi2009/2010的DES加密单元
    升级Delphi2010时text字段问题
    JS的encodeURI编码后,PHP解码方法
    Indy发送邮件被kbas退掉
    关于Delphi2010使用Indy发送邮件乱码问题的解决
  • 原文地址:https://www.cnblogs.com/yaoyuan2/p/9606504.html
Copyright © 2011-2022 走看看