1. 程式人生 > >java-多執行緒-執行緒池

java-多執行緒-執行緒池

       執行緒池本質是一種空間換時間的思想

       需要處理非常多請求時候,如果每一個請求都開啟一個新執行緒的話,系統就要不斷的進行執行緒的建立和銷燬,是一項十分消耗資源的操作,且當執行緒數量太多時,系統不一定能受得了。

  • 通過複用執行緒池中的執行緒,來避免不斷的建立和銷燬執行緒給系統帶來的效能開銷。
  • 對執行緒進行一些維護和管理,比如定時開始,週期執行,併發數控制/限制。

Java通過Executors提供四種執行緒池,分別為:

        ExecutorService cachedThreadPool     = Executors.newCachedThreadPool();
        ExecutorService fixedThreadPool      = Executors.newFixedThreadPool(5);
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        ExecutorService scheduledThreadPool  = Executors.newScheduledThreadPool(5);
  •  newCachedThreadPool:建立一個可快取執行緒池,如果執行緒池長度超過處理需要,可靈活回收空閒執行緒,若無可回收,則新建執行緒。(執行緒最大併發數不可控制)
  • newFixedThreadPool:建立一個定長執行緒池,可控制執行緒最大併發數,超出的執行緒會在佇列中等待。
  • newScheduledThreadPool:建立一個定長執行緒池,支援定時及週期性任務執行。
  • newSingleThreadExecutor:建立一個單執行緒化的執行緒池,它只會用唯一的工作執行緒來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先順序)執行。

檢視這幾種執行緒池實現方式我們發現一個重要的類:ThreadPoolExecutor

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 ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
}
public class Executors {
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
}
public class ScheduledThreadPoolExecutor
        extends ThreadPoolExecutor
        implements ScheduledExecutorService {
    public ScheduledThreadPoolExecutor(int corePoolSize) {
            super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
                  new DelayedWorkQueue());
    }
}

ThreadPoolExecutor

ThreadPoolExecutor是執行緒池的真正實現,他通過構造方法的一系列引數,來構成不同配置的執行緒池。

public class ThreadPoolExecutor extends AbstractExecutorService {
    ......
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             threadFactory, defaultHandler);
    }
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              RejectedExecutionHandler handler) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), handler);
    }
    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:核心執行緒數。預設一直存活,即使閒置也不會受keepAliveTime限制。除非將allowCoreThreadTimeOut設定為true
  • maximumPoolSize:最大執行緒數。超出的執行緒將被阻塞。當任務佇列為沒有設定大小的LinkedBlockingDeque時,這個值無效。
  • keepAliveTime:非核心執行緒的閒置超時時間。超過這個時間就會被回收。
  • unit:指定keepAliveTime的單位,如TimeUnit.SECONDS。當將allowCoreThreadTimeOut設定為true時對corePoolSize生效。
  • workQueue:執行緒池中的任務佇列。常用的有三種佇列,SynchronousQueue,LinkedBlockingDeque,ArrayBlockingQueue
  • threadFactory:執行緒工廠,提供建立新執行緒的功能。
  • handler:當執行緒池中的資源已經全部使用,新增新執行緒被拒絕時,會呼叫RejectedExecutionHandler的rejectedExecution方法。

瞭解了構造方法的引數之後我們就可以自己定製執行緒池了。