Java多线程--2、ThreadPoolExecutor详解(一)

      ThreadPoolExecutor作为多线程开发的核心类,也是各大厂的面试必问题目,身为一个Javaer,是有必要去详细的了解一下他的运行原理的。

      ThreadPoolExecutor的构造方法源码(看不懂英文的同学出门右转):

/**
 * 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:<br>
 *         {@code corePoolSize < 0}<br>
 *         {@code keepAliveTime < 0}<br>
 *         {@code maximumPoolSize <= 0}<br>
 *         {@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<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;
}

   几个重要的参数的含义是必须要掌握的,本文不再一一叙述,下面主要介绍一下通过ThreadPoolExecutor是如何创建线程的。

      首先看一下几个比较重要的全局变量与方法:

private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

// runState is stored in the high-order bits
private static final int RUNNING    = -1 << COUNT_BITS;
private static final int SHUTDOWN   =  0 << COUNT_BITS;
private static final int STOP       =  1 << COUNT_BITS;
private static final int TIDYING    =  2 << COUNT_BITS;
private static final int TERMINATED =  3 << COUNT_BITS;

// Packing and unpacking ctl
private static int runStateOf(int c)     { return c & ~CAPACITY; }
private static int workerCountOf(int c)  { return c & CAPACITY; }
private static int ctlOf(int rs, int wc) { return rs | wc; }

       ThreadPoolExecutor是通过ctl变量来保存当前的线程池的一些信息的,ctl是一个原子整型的变量,保证了其独有的原子性,实际保存的是一个32位的二进制数(在win平台上,下文中只以32位为基准),保存的信息如下图:

     几个比较重要的全局变量如下:

     2个常量:

  1. COUNT_BITS:整型变量的长度减3,用于移位用,可以保证数字的前3位用来标识状态。
  2. CAPACITY:容量,用于保存当前线程池中的线程数量,是一个前3位为0,后面全部29位全部为1的数字(0001 1111 1111 1111 1111 1111 1111 1111)。这样其他的数字和他做与操作时,前3位保证为0,后29位保留原来的数字。

     5个状态常量:RUNING < SHUTDOWN < STOP < TIDYING < TERMINATED,通过左移位29位,空位补0的方式,保证一个前3位的状态标识。

    3个常用方法:

  1. runStateOf:参数通常为当前ctl的值(通过ctl.get()获取),然后让其与~CAPACITY(1110 0000 0000 0000 0000 0000 0000 0000)做&运算,结果为前3位保留原有值,后29位为0,得出状态信息。
  2. workerCountOf:同上,不过与CAPACITY(0001 1111 1111 1111 1111 1111 1111 1111)做&运算,结果为前3位为0,后29位为原值,得出线程数量信息。
  3. ctlOf:参数为runState(后29位都为0)、workerCount(前3位都为0),进行或操作后,前3位保留runState的值,后29位保留workerCount的值,即为当前线程池的全部状态信息。

    后续的操作中,会经常性的出现以上的变量及方法,请各位谨记。 

    下一篇:ThreadPoolExecutor的execute方法解析:

    https://my.oschina.net/u/3760321/blog/1615188

猜你喜欢

转载自my.oschina.net/u/3760321/blog/1615152