Executor原理解析

1、Executor 線程池體系介紹

1. Executor 框架體系介紹

  • Executor: java線程池框架的最上層父接口,在Executor中只有executor()方法,該方法表示提交Runnable類型線程池並執行。java

  • ExecutorService: Executor的子接口,該接口中submit()方法可接收Runnable參數或Callable參數,在使用結束後使用shutdown()方法關閉線程池,再也不接收新的任務。緩存

  • AbstractExecutorService: ExecutorService的默認實現類。框架

  • ScheduledExecutorService: ExecutorService的子接口,可供定時任務調度的接口。工具

  • ScheduledThreadPoolExecutor: 提供了另外一種線程池,延遲執行和週期性執行的線程池。this

  • ThreadPoolExecutor: Java線程池最核心的一個類,該類繼承自AbstractExecutorService主要功能是建立線程池,給任務分配線程資源,執行任務。線程

2. 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.acc = System.getSecurityManager() == null ?
                null :
                AccessController.getContext();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }

2、Executors 線程池工具類

1. newFixedThreadPool: 固定大小線程池

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }
  • corePoolSize與maximumPoolSize相等,即其線程全爲核心線程,是一個固定大小的線程池,是其優點;
  • keepAliveTime = 0 該參數默認對核心線程無效,而FixedThreadPool所有爲核心線程;
  • workQueue 爲LinkedBlockingQueue(無界阻塞隊列),隊列最大值爲Integer.MAX_VALUE。若是任務提交速度持續大餘任務處理速度,會形成隊列大量阻塞。由於隊列很大,頗有可能在拒絕策略前,內存溢出。是其劣勢;
  • FixedThreadPool的任務執行是無序的;

2. newSingleThreadExecutor: 單線程化線程池

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(),
                                    threadFactory));
    }
  • 控制線程池中corePoolSize與maximumPoolSize都爲1
  • FinalizableDelegatedExecutorService繼承DelegatedExecutorService,DelegatedExecutorService最終繼承AbstractExecutorService,該類是線程池的一個代理模式的實現,相比於ThreadPoolExecutor閹割一部分功能,造成線程池單例化。

3. newCachedThreadPool: 可緩存線程池

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>(),
                                      threadFactory);
    }
  • corePoolSize = 0,maximumPoolSize = Integer.MAX_VALUE,即線程數量幾乎無限制
  • keepAliveTime = 60s,60s後空閒線程自動結束
  • SynchronousQueue 爲同步隊列,入隊出隊必須同時傳遞,由於CachedThreadPool線程建立無限制,不會有隊列等待

4. newScheduledThreadPool: 週期性線程池

public static ScheduledExecutorService newScheduledThreadPool(
            int corePoolSize, ThreadFactory threadFactory) {
        return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
    }
  • newScheduledThreadPool爲定長線程池,限定核心線程數
  • ScheduledThreadPoolExecutor方法中對線程池參數作了進一步的封裝,設置maximumPoolSize = Integer.MAX_VALUE,keepAliveTime = 0
  • 調用scheduleAtFixedRate()方法可進行週期性任務設置

5. newWorkStealingPool: 工做竊取線程池(jdk1.8)

public static ExecutorService newWorkStealingPool(int parallelism) {
        return new ForkJoinPool
            (parallelism,
             ForkJoinPool.defaultForkJoinWorkerThreadFactory,
             null, true);
    }
  • ForkJoinPool繼承AbstractExecutorService,ForkJoinPool能夠充分利用多核cpu的優點,將一個任務拆分紅多個「小任務」並行計算,提升任務的執行時間
相關文章
相關標籤/搜索