面试问题Executors有哪些创建线程池的方法
原创
©著作权归作者所有:来自51CTO博客作者云原生总监的原创作品,请联系作者获取转载授权,否则将追究法律责任
下面四个方法本质上都是调用ThreadPoolExecutor的构造方法:
1:Executors.newSingleThreadExecutor()
2:Executors.newFixedThreadPool(nThreads)
3:Executors.newCachedThreadPool()
4:Executors.newScheduledThreadPool(corePoolSize)
corePoolSize:线程池中保留的线程数量,即使这些线程是处于空闲状态
maximumPoolSize:线程池中可创建的最大线程数量
keepAliveTime:当线程数大于corePoolSize数量时,如果线程空闲,这个线程在这个空闲时间后将会销毁
unit:keepAliveTime时间单位
workQueue:任务队列
1:Executors.newSingleThreadExecutor()创建单线程任务线程池
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
2:Executors.newFixedThreadPool(nThreads)创建固定数量线程线程池
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
3:Executors.newCachedThreadPool()创建以默认60秒为空闲时间的缓存线程池,核心线程数为0
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
4:Executors.newScheduledThreadPool(corePoolSize)创建可以控制执行时间的线程池
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue());
}