缓存线程池(newCachedThreadPool)

缓存线程池(newCachedThreadPool)

package com.zhw.learning.thread;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhw
 * 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,
 * 若无可回收,则新建线程
 */
public class CachedThreadPoolTest {

    public static void main(String[] args) {

        /**
         * 1.创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程,
         *  那么就会回收部分空闲(60秒不执行任务)的线程
         * 2.当任务数增加时,此线程池又可以智能的添加新线程来处理任务
         * 3.此线程池不会对线程池大小做限制,
         *  线程池大小完全依赖于操作系统(或者说JVM)能够创建的最大线程大小
         *
         *  Executors.newCachedThreadPool()源码:
         *  public static ExecutorService newCachedThreadPool() {
         *         return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
         *                                       60L, TimeUnit.SECONDS,
         *                                       new SynchronousQueue<Runnable>());
         *  }
         *
         */
        ExecutorService cahedThreadPool = Executors.newCachedThreadPool();

        for (int i=0;i<5;i++){
            final int index = i;
            cahedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat(
                                "HH:mm:ss");
                        System.out.println("运行时间: " +
                                sdf.format(new Date()) + " " + index);
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        cahedThreadPool.shutdown();

    }

}

因为这种线程有新的任务提交,就会创建新的线程(线程池中没有空闲线程时),不需要等待,所以提交的5个任务的运行时间是一样的,运行结果如下:
在这里插入图片描述

发布了31 篇原创文章 · 获赞 5 · 访问量 624

猜你喜欢

转载自blog.csdn.net/qq_37365741/article/details/103889592
今日推荐