TheadPoolExecutor源码分析
TheadPoolExecutor源码分析 ThreadPoolExecutor是多线程中经常用到的类,其使用一个线程池执行提交的任务。 实现 没有特殊需求的情况下,通常都是用Executors类的静态方法如newCachedThreadPoll来初始化ThreadPoolExecutor实例: public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); } 从Executors的方法实现中看出,BlockingQueue使用的SynchronousQueue,底层使用了栈的实现。值得注意的是,这个SynchronousQueue是没有容量限制的,Executors也将maximumPoolSize设为Integer.MAX_VALUE。 ThreadPoolExecutor的构造方法: 按照javadoc的解释: corePoolSize是池中闲置的最小线程数 maximumPoolSize是池中允许的最大线程数 keepAliveTime是线程数大于最小线程数时,过量闲置线程的最大存活时间 unit是上面存活时间的单位 workQueue是用来暂时保存运行前的任务 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) public void execute(Runnable command) { if (command == null) throw new NullPointerException(); int c = ctl.