标签:imp data- thinking 问题 div 限制 通过 system def
//首先看Executors中通过newCachedThreadPool创建线程池的方法的源码 //此方法是通过new一个ThreadPoolExecutor来创建的 //这个构造方法有5个参数: //第一个参数corePoolSize(核心池大小)为0, //第二个参数maximumPoolSize(最大线程池大小)为Integer.MAX_VALUE无限大,源码中是:public static final int MAX_VALUE = 0x7fffffff; //第三个参数keepAliveTime(线程存货的时间)是60秒,意味着线程空闲时间超过60秒就会被杀死。 //第五个参数采用SynchronousQueue装等待的任务,这个阻塞队列没有存储空间,这意味着只要有请求到来,就必须要找到一条工作线程处理他, // 如果当前没有空闲的线程,那么就会再创建一条新的线程。 public class Executors { public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } } //ThreadPoolExecutor类中此构造函数源码: public class ThreadPoolExecutor extends AbstractExecutorService { public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } }
public class LiftOff implements Runnable { protected int countDown = 5; private static int taskCount = 0; private final int id = taskCount++; public LiftOff() { } public LiftOff(int countDown) { this.countDown = countDown; } public String status() { return "# " + id + " ( " + (countDown > 0 ? countDown : "LiftOff !") + " )"; } @Override public void run() { while (countDown-- > 0) { System.out.println(status()); Thread.yield(); } } }
public class CachedThreadPool { public static void main(String[] args) { ExecutorService executorService = Executors.newCachedThreadPool(); for (int i = 0; i < 3; i++) { executorService.execute(new LiftOff()); } } } 结果: # 2 ( 4 ) # 0 ( 4 ) # 1 ( 4 ) # 2 ( 3 ) # 0 ( 3 ) # 2 ( 2 ) # 1 ( 3 ) # 2 ( 1 ) # 0 ( 2 ) # 2 ( LiftOff ! ) # 1 ( 2 ) # 0 ( 1 ) # 1 ( 1 ) # 0 ( LiftOff ! ) # 1 ( LiftOff ! )
标签:imp data- thinking 问题 div 限制 通过 system def
原文地址:https://www.cnblogs.com/whx20100101/p/9862382.html