newFixedTreadPool:返回一个固定线程数量的线程池,该方法创建的线程池线程数量始终不变,此线程池使用的任务队列为LinkedBlockingQueue。(任务队列描述说明链接:ThreadPoolExecutor主要参数说明_誰嘚的博客-CSDN博客)
newSingleThreadExecutor:返回一个只有一个线程的线程池,此线程池使用的任务队列为LinkedBlockingQueue。
newCachedThreadPool:返回一个可根据实际情况调整线程数量的线程池,线程池线程数量不确定,但若有空闲的线程可以复用,则会优先使用可复用的线程。若所有线程均在工作,则会创建线程处理任务,所有线程在当前任务执行完毕后,将返回线程池进行复用。此线程池使用的任务队列为SynchronousQueue。
newScheduledThreadPool:返回一个ScheduledExecutorService对象,但该线程池可以指定线程数量。
------------------
ScheduledExecutorService接口主要方法介绍:
/*
*给定时间对任务进行一次调度
*/
public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);
/*
*给定时间对任务进行周期性调度,以开始时间为起点,之后的period时间,调度下一次任务
*/
public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);
/*
*给定时间对任务进行周期性调度,以任务结束时间为起点,再经过delay时间,调度下一次任务
*/
public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);
-------------------
无论是newFixedThreadPool、newSingleThreadExecutor还是newCachedThreadPool都是使用ThreadPoolExecutor实现的,具体如下:
public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory); }
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }