上篇文章我们讲解了这个线程池工厂类的用法,介绍了它所提供的一些常用线程池工具的用法,今天我们来继续深入学习。

一、

上面我们着重介绍了通过 工具类获得的各类连接池的使用。上面的几个连接池中,除了 这个连接池,剩下的连接池,其实底层都是使用 来创建的。包括ol() 底层是通过 类构建的,而 类本身也是的子类。

所以 类是线程池中非常重要的一个类,也是面试过程中的一个高频考点。今天我们来重点聊聊。

1.1 类中线程池解读

首先我们先看一下上面的几个连接池的底层实现方式:

tor

public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue()));
    }

代码中我们可以看到,这个单线程的线程池,创建了一个 对象,然后又将其包装成了 对象。

这里我们重点要观察创建 的构造参数:先列出来,后面比较。

new ThreadPoolExecutor(1, 1,
                            0L, TimeUnit.MILLISECONDS,
                            new LinkedBlockingQueue())

public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue());
    }

public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue());
    }

ol

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}
// ScheduledThreadPoolExecutor
public ScheduledThreadPoolExecutor(int corePoolSize) {
    // super就是调用ThreadPoolExecutor 的构造方法
    super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
          new DelayedWorkQueue());
}

通过上面的代码解读,我们发现,创建线程池基本都是直接或间接调用 的构造方法实现的,那么我们很有必要了解一下这个类。

1.2 类

这个类就是Java中提供给我们用于创建线程池的类。而在《阿里巴巴-Java开发手册》中也明确提到了,不要使用创建线程池,而是通过的方式创建,这样的处理方式能让编写代码的人更加明确线程池的运行规则,规避资源耗尽的风险。所以如果我们需要使用线程池,尽量通过 去创建,那么我们有必要了解一下类创建线程池的方法:

类中共有四个构造方法

线程池拒绝策略使用场景_线程池拒绝策略_线程池拒绝策略详解

这种多个构造方法的,一般参数最多的就是最核心的,因为内部基本都是调用的参数最多的,只不过有一些传入了一些默认参数而已。

那么我们就来看一下参数最多的构造方法:

    /**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:
     *         {@code corePoolSize < 0}
     *         {@code keepAliveTime < 0}
     *         {@code maximumPoolSize <= 0}
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue 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;
    }

参数的含义如下:

线程池执行线程任务的主要流程是:

一个任务通过 ()方法被添加到线程池,任务就是一个 类型的对象,任务的执行方法就是类型对象的run()方法。当一个任务通过()方法欲添加到线程池时:

1.3 线程池中的重要参数-阻塞队列

接下我们介绍一下 线程池中的比较重要的参数:

,这个队列是一个 , 也就是一个 类型的阻塞队列,类型很好理解,就是我们等待执行的任务么,放到这个队列中。那么什么是呢:

:即阻塞队列,什么是阻塞队列呢,就是在某些情况下对阻塞队列的访问可能会造成阻塞。主要有两种情况:

那么线程池中为什么要使用阻塞队列呢?我们就以取数据为例,使用阻塞队列可以保证如果队列为空的时候,在读取数据时这个方法是阻塞的,当我们此时又来了一个任务,有可以保证新来的任务能够被获取出来。如果不适用阻塞队列,我们就需要设计一个新加入数据时同时线程来拿数据,这个就比较麻烦了,而使用阻塞队列就可以解决这个问题。

同理当队列满的时候,添加元素是阻塞的,直到有队列中有位置,这样就可以保证的在合理利用资源的前提下,新加入的数据不丢失。

在线程池中常用的阻塞队列实现有如下几个:

大家在选择的时候,还是要根据具体的使用场景,要考虑到线程执行的任务的时间,数据可丢失的忍受程度,内存的大小等进行合理的选择,有时候选择不慎,就会导致线程池的使用出现一些系统级别的问题。

1.4 拒绝策略

什么是拒绝策略呢?

JDK主要提供了4种饱和策略供选择。4种策略都做为静态内部类在中进行实现。

拒绝策略提供顶级接口 dler ,其中方法 即定制具体的拒绝策略的执行逻辑。

jdk默认提供了四种拒绝策略:

了解了上面的这些概念,我们反过来再看看我们之前的线程池工具:我们以 为例:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue());
}

调用 的构造方法, 将核心线程数和最大线程数都设置为我们的参数,所以也就代表了这个线程池中的线程数量最大就是 我们传入的参数。同时持续时间为0秒,代表线程如果没有任务了就会自动销毁。

该线程池使用了 阻塞队列,这是属于无界的阻塞队列,也就是当我的线程都被占用,如果还有任务不断放入队列中,当任务堆积到一定程度,就到导致java内存溢出。

这里没有显示的传递拒绝策略参数。我们到构造方法中继续查看:

线程池拒绝策略使用场景_线程池拒绝策略_线程池拒绝策略详解

发现如果不传的话使用的是默认的拒绝策略:

线程池拒绝策略使用场景_线程池拒绝策略详解_线程池拒绝策略

而默认的拒绝策略就是: : 丢弃任务,并抛出拒绝执行 异常信息。

剩下几个大家也可以尝试去读一下代码。

二、线程池源码浅析

当我们创建了不同类型的线程池,本质上就是 中的参数值不同,比如核心线程数,最大线程数,拒绝策略和阻塞队列等。

当我们提交一个线程任务的时候,执行的是线程池中的 方法:

线程池拒绝策略详解_线程池拒绝策略使用场景_线程池拒绝策略

方法回去调用线程池中和核心方法: ()

线程池拒绝策略使用场景_线程池拒绝策略_线程池拒绝策略详解

在方法中会根据我们的核心线程数好队列中的任务获取情况来判断,该任务是接收还是拒绝,拒绝的话就会直接调用我们拒绝策略中的 方法。 接收的话,就会调用 方法。这里面使用原子量 clt用来做一致性校验。

在中,会使用锁,状态,CAS进行判断,并把封装成类型,创建线程来执行相关任务。

———END———
限 时 特 惠: 本站每日持续更新海量各大内部创业教程,永久会员只需109元,全站资源免费下载 点击查看详情
站 长 微 信: nanadh666

声明:1、本内容转载于网络,版权归原作者所有!2、本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。3、本内容若侵犯到你的版权利益,请联系我们,会尽快给予删除处理!