Executors
Executors提供了一些方便创建TreadPoolExecutors的方法,主要有以下几个:
newFixedThreadPool(int)
创建一个固定大小线程池。从下面的代码我们可以看出,corePoolSize需要指定,即即使空闲没有任务执行也一直启动的线程,newFixedThreadPool把ThreadPoolExecutor中的keepAliveTime设置为0,即ThreadPoolExecutor中启动的线程数量启动后就一直运行,并不会由于在keepAliveTime的时间内仍没有任务执行而退出。缓冲任务的队列使用的是LinkedBlockingQueue,如果放入线程池中的任务数量(最大为整数的最大值)比线程池中的线程多时,则会把多余的任务放到队列里。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
newSingleThreadExecutor()
相当于创建了只有一个线程的固定大小线程池,使用此线程池的时候,并行执行的任务只有一个,其他的任务都放到LinkedBlockingQueue队列中
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
newCachedThreadPool()
创建一个带缓存的线程池,从下面代码可以看出,newCachedThreadPool把ThreadPoolExecutor中的corePoolSize设置为0,即不允许有空闲的线程,最大线程数量为整数的最大值,线程的keepAliveTime为60秒,即如果60秒这个线程还没有任务执行,则退出。缓存任务的队列为SynchronousQueue,在使用时,放入newCachedThreadPool的任务都会复用线程或者启动新线程来执行,随着放入的任务的数量的增加,newCachedThreadPool中新启动的线程数量也随之增加,直到整数的最大值,则抛出异常。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
newScheduledThreadPool(int)
创建一个定时线程池,其中corePoolSize(即使空闲也不会退出的线程数量)需要指定,最大线程数量为整数的最大值,线程的keepAliveTime为0,即不设置线程的空闲时间,缓存任务的队列为DelayedWorkQueue,即任务数量超过线程池中的线程数量,则把任务放到DelayedWorkQueue队列里缓存。在实际业务中,通常会有一些需要定时或者延迟执行的任务,此时,newScheduledThreadPool是个不错的选择。当然在jdk5前可以用Timer来实现,但是Timer只能单线程。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}