1. 程式人生 > >java之執行緒池面試題

java之執行緒池面試題

面試官:執行緒池有哪些?分別的作用是什麼?

常用的執行緒池有:

  1. newSingleThreadExecutor
  2. newFixedThreadExecutor
  3. newCacheThreadExecutor
  4. newScheduleThreadExecutor

1、newSingleThreadExecutor:

  單個執行緒的執行緒池,即執行緒池中每次只有一個執行緒工作,單執行緒序列執行任務;

2、newFixedThreadExecutor:

  固定數量的執行緒池,每提交一個任務就是一個執行緒,直到執行緒達到執行緒池的最大數量,然後後面進入等待佇列直到前面的任務才繼續執行;

3、newCacheThreadExecutor:

  可快取執行緒池,當執行緒池大小超過了處理任務所需的執行緒,那麼就會回收部分空閒(一般 是60秒無執行)的執行緒,當有任務時,會新增新執行緒來執行;

4、newScheduleThreadExecutor:

  大小無限制的 執行緒池,支援定時和週期性的執行執行緒。

 

ThreadPoolExecutor解說:

ThreadPoolExecutor是上面幾個執行緒池底層的實現;

其中完整的構造方法是:

public ThreadPoolExecutor(int corePoolSize,
                              
int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
  • corePoolSize:執行緒池中所儲存的執行緒數,包括空閒執行緒;
  • maximumPoolSize:執行緒池中允許的最大執行緒數;
  • keepAliveTime:執行緒存活時間,當超過keepAliveTime的時候後還無法獲取新的任務,則返回null;
  • unit:keepAliveTime引數的時間單位;
  • workQueue:執行前用於保持任務的佇列,此佇列僅保持由execute方法提交的Runnable任務;
  • threadFactory:執行程式建立新執行緒時使用的工廠;
  • handler:由於超出執行緒範圍和佇列容量而使用執行被阻塞時所使用的處理策略;