来看一下线程池封装类对于ThreadPoolExecutor的调用:
newSingleThreadExecutor对ThreadPoolExecutor的封装源码如下:
public static ExecutorService newSingleThreadExecutor() { return new Executors.FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()));}复制代码newCachedThreadPool对ThreadPoolExecutor的封装源码如下:
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());}复制代码newFixedThreadPool对ThreadPoolExecutor的封装源码如下:
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());}复制代码ScheduledExecutorService对ThreadPoolExecutor的封装源码如下:
public static ScheduledExecutorService newSingleThreadScheduledExecutor() { return new DelegatedScheduledExecutorService (new ScheduledThreadPoolExecutor(1));}复制代码newSingleThreadScheduledExecutor使用的是ThreadPoolExecutor的子类ScheduledThreadPoolExecutor,如下图所示:
newScheduledThreadPool对ThreadPoolExecutor的封装源码如下:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize);}复制代码newScheduledThreadPool使用的也是ThreadPoolExecutor的子类ScheduledThreadPoolExecutor。 2.3 线程池状态查看ThreadPoolExecutor源码可知线程的状态如下: