1. 程式人生 > >線程池(3)Executors.newCachedThreadPool

線程池(3)Executors.newCachedThreadPool

核心 ger exceptio @override ice trace catch nts val

例子:

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