1)FixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
FixedThreadPool适用于为了满足资源管理的需求,而需要限制当前线程数量的应用场
景,它适用于负载比较重的服务器。
2)SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
SingleThreadExecutor适用于需要保证顺序地执行各个任务;并且在任意时间点,不会有多
个线程是活动的应用场景。
3)CachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
CachedThreadPool是大小无界的线程池,适用于执行很多的短期异步任务的小程序,或者
是负载较轻的服务器。
(2)ScheduledThreadPoolExecutor
ScheduledThreadPoolExecutor通常使用工厂类Executors来创建。Executors可以创建2种类
型的ScheduledThreadPoolExecutor,如下。
·ScheduledThreadPoolExecutor。包含若干个线程的ScheduledThreadPoolExecutor。
·SingleThreadScheduledExecutor。只包含一个线程的ScheduledThreadPoolExecutor。
下面分别介绍这两种ScheduledThreadPoolExecutor。
下面是工厂类Executors提供的,创建固定个数线程的ScheduledThreadPoolExecutor的API。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize,ThreadFactory threadFactory)
ScheduledThreadPoolExecutor适用于需要多个后台线程执行周期任务,同时为了满足资源
管理的需求而需要限制后台线程的数量的应用场景。下面是Executors提供的,创建单个线程
的SingleThreadScheduledExecutor的API。
public static ScheduledExecutorService newSingleThreadScheduledExecutor()
public static ScheduledExecutorService newSingleThreadScheduledExecutor
(ThreadFactory threadFactory)
SingleThreadScheduledExecutor适用于需要单个后台线程执行周期任务,同时需要保证顺
序地执行各个任务的应用场景。
**自己的见解:Spring框架中已经有定时器的实现,做定时任务的话感觉可以直接用Spring封装的定时器