線程池(3)Executors.newCachedThreadPool

來源:互聯網
上載者:User

標籤:.sh   getname   current   print   live   ice   ack   exe   rac   

例子:

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

 

線程池(3)Executors.newCachedThreadPool

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.