面试问题Executors有哪些创建线程池的方法

下面四个方法本质上都是调用ThreadPoolExecutor的构造方法:

1:Executors.newSingleThreadExecutor()

2:Executors.newFixedThreadPool(nThreads)

3:Executors.newCachedThreadPool()

4:Executors.newScheduledThreadPool(corePoolSize)


面试问题Executors有哪些创建线程池的方法

corePoolSize:线程池中保留的线程数量,即使这些线程是处于空闲状态

maximumPoolSize:线程池中可创建的最大线程数量

keepAliveTime:当线程数大于corePoolSize数量时,如果线程空闲,这个线程在这个空闲时间后将会销毁

unit:keepAliveTime时间单位

workQueue:任务队列


1:Executors.newSingleThreadExecutor()创建单线程任务线程池

[java] view plain copy
  1. public static ExecutorService newSingleThreadExecutor() {  
  2.         return new FinalizableDelegatedExecutorService  
  3.             (new ThreadPoolExecutor(11,  
  4.                                     0L, TimeUnit.MILLISECONDS,  
  5.                                     new LinkedBlockingQueue<Runnable>()));  
  6.     }  
2:Executors.newFixedThreadPool(nThreads)创建固定数量线程线程池

[java] view plain copy
  1. public static ExecutorService newFixedThreadPool(int nThreads) {  
  2.        return new ThreadPoolExecutor(nThreads, nThreads,  
  3.                                      0L, TimeUnit.MILLISECONDS,  
  4.                                      new LinkedBlockingQueue<Runnable>());  
  5.    }  
3:Executors.newCachedThreadPool()创建以默认60秒为空闲时间的缓存线程池,核心线程数为0

[java] view plain copy
  1. public static ExecutorService newCachedThreadPool() {  
  2.         return new ThreadPoolExecutor(0, Integer.MAX_VALUE,  
  3.                                       60L, TimeUnit.SECONDS,  
  4.                                       new SynchronousQueue<Runnable>());  
  5.     }  
4:Executors.newScheduledThreadPool(corePoolSize)创建可以控制执行时间的线程池

[java] view plain copy
  1. public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {  
  2.         return new ScheduledThreadPoolExecutor(corePoolSize);  
  3.     }  


[java] view plain copy
  1. public ScheduledThreadPoolExecutor(int corePoolSize) {  
  2.        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,  
  3.              new DelayedWorkQueue());  
  4.    }