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的优点,将一个任务拆分红多个“小任务”并行计算,提升任务的执行时间
相关文章
相关标签/搜索