public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler){ ...... }
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
咱们经过查看ScheduledThreadPoolExecutor的源代码,能够发现ScheduledThreadPoolExecutor继承了ThreadPoolExecutor。java
public ScheduledThreadPoolExecutor(int corePoolSize, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue(), threadFactory, handler); }
从构造中发现ScheduledThreadPoolExecutor线程池实际上是调用了ThreadPoolExecutor构造进行实现的,只是ThreadPoolExecutor使用的工做队列是java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue经过名字咱们均可以猜到这个是一个延时工做队列。
由于ScheduledThreadPoolExecutor的最大线程是Integer.MAX_VALUE,并且根据源码能够看到execute和submit其实都是调用schedule这个方法,并且延时时间都是指定为0,因此调用execute和submit的任务都直接被执行。算法
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }
ScheduledThreadPoolExecutor 提供了3种延迟执行策略缓存
schedule(commod,delay,unit) ,这个方法是说系统启动后,须要等待多久执行,delay是等待时间。只执行一次,没有周期性。服务器
scheduleAtFixedRate(commod,initialDelay,period,unit),固定速率执行周期任务。这个是以period为固定周期时间,按照必定频率来重复执行任务,initialDelay是说系统启动后,须要等待多久才开始执行。并发
scheduleWithFixedDelay(commod,initialDelay,delay,unit),固定延迟执行周期任务。这个是以delay为固定延迟时间,按照必定的等待时间来执行任务,initialDelay意义与上面的相同。函数
在Java 7中引入了一种新的线程池:ForkJoinPool。
它同ThreadPoolExecutor同样,也实现了Executor和ExecutorService接口。它使用了一个无限队列来保存须要执行的任务,而线程的数量则是经过构造函数传入,若是没有向构造函数中传入但愿的线程数量,那么当前计算机可用的CPU数量会被设置为线程数量做为默认值。spa
public static ExecutorService newWorkStealingPool() { return new ForkJoinPool (Runtime.getRuntime().availableProcessors(), ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); }
并发数默认为当前系统cpu个数。线程
public static ExecutorService newWorkStealingPool(int parallelism) { return new ForkJoinPool (parallelism, ForkJoinPool.defaultForkJoinWorkerThreadFactory, null, true); }
也能够指定并行数。code