下面四个方法本质上都是调用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>()));
- }
- public static ExecutorService newFixedThreadPool(int nThreads) {
- return new ThreadPoolExecutor(nThreads, nThreads,
- 0L, TimeUnit.MILLISECONDS,
- new LinkedBlockingQueue<Runnable>());
- }
- public static ExecutorService newCachedThreadPool() {
- return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
- 60L, TimeUnit.SECONDS,
- new SynchronousQueue<Runnable>());
- }
- public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
- return new ScheduledThreadPoolExecutor(corePoolSize);
- }
- public ScheduledThreadPoolExecutor(int corePoolSize) {
- super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
- new DelayedWorkQueue());
- }
本文详细介绍了Java中四种常见的线程池实现方式:单线程任务线程池、固定数量线程线程池、默认60秒为空闲时间的缓存线程池以及可以控制执行时间的线程池。每种线程池都提供了具体的构造方法和参数说明。

被折叠的 条评论
为什么被折叠?



