ThreadPoolExecutor学习笔记(一)

159 阅读3分钟

ThreadPoolExecutor设计原理

image.png

构造方法

最常被问到的Java线程池构造方法有几个参数,就行下面这7个

/**
* @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
*/
public ThreadPoolExecutor(int corePoolSize, //核心线程数
                          int maximumPoolSize,//最大线程数
                          long keepAliveTime,// 大于corePoolSize的线程空闲存活时间
                          TimeUnit unit,//时间单位
                          BlockingQueue<Runnable> workQueue,//任务队列
                          ThreadFactory threadFactory,//线程工厂
                          RejectedExecutionHandler handler)//拒绝策略

线程工厂很简单,就一个接口

public interface ThreadFactory {

    /**
     * Constructs a new {@code Thread}.  Implementations may also initialize
     * priority, name, daemon status, {@code ThreadGroup}, etc.
     *
     * @param r a runnable to be executed by new thread instance
     * @return constructed thread, or {@code null} if the request to
     *         create a thread is rejected
     */
    Thread newThread(Runnable r);
}

拒绝策略

public interface RejectedExecutionHandler {

    /**
     * Method that may be invoked by a {@link ThreadPoolExecutor} when
     * {@link ThreadPoolExecutor#execute execute} cannot accept a
     * task.  This may occur when no more threads or queue slots are
     * available because their bounds would be exceeded, or upon
     * shutdown of the Executor.
     *
     * <p>In the absence of other alternatives, the method may throw
     * an unchecked {@link RejectedExecutionException}, which will be
     * propagated to the caller of {@code execute}.
     *
     * @param r the runnable task requested to be executed
     * @param executor the executor attempting to execute this task
     * @throws RejectedExecutionException if there is no remedy
     */
    void rejectedExecution(Runnable r, ThreadPoolExecutor executor);
}

线程池提供的拒绝策略有4个:

  • CallerRunsPolicy 调用者执行
  • AbortPolicy 拒绝执行,抛出RejectedExecutionException异常 线程池默认的拒绝策略
  • DiscardPolicy 默默的丢弃
  • DiscardOldestPolicy 丢弃最老的
/**
 * The default rejected execution handler
 */
private static final RejectedExecutionHandler defaultHandler = new AbortPolicy();

线程池状态

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; }

工作线程数和线程池状态都记录在ctl中,通过runStateOf、workerCountOf、ctlOf三个方法可以获取。

  • 状态说明
*   RUNNING:  Accept new tasks and process queued tasks 接受新任务,处理任务队列中的任务
*   SHUTDOWN: Don't accept new tasks, but process queued tasks 不接受新任务,处理任务队列中的任务
*   STOP:     Don't accept new tasks, don't process queued tasks,
*             and interrupt in-progress tasks  不接受新任务,不处理任务队列中的任务
*   TIDYING:  All tasks have terminated, workerCount is zero, 
*             the thread transitioning to state TIDYING
*             will run the terminated() hook method 所有任务都停止,待处理任务为0,线程转换为TIDYING,将会执行terminated()钩子函数
*   TERMINATED: terminated() has completed terminated()执行完成
  • 状态之间的转换
* RUNNING -> SHUTDOWN
*    On invocation of shutdown(), perhaps implicitly in finalize()
* (RUNNING or SHUTDOWN) -> STOP
*    On invocation of shutdownNow()
* SHUTDOWN -> TIDYING
*    When both queue and pool are empty
* STOP -> TIDYING
*    When pool is empty
* TIDYING -> TERMINATED
*    When the terminated() hook method has completed

execute方法

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    int c = ctl.get();
    if (workerCountOf(c) < corePoolSize) {//当前线程数小于核心线程数
        if (addWorker(command, true))//直接添加核心线程,并把command放到线程池中执行
            return;
        c = ctl.get();
    }
    if (isRunning(c) && workQueue.offer(command)) {//达到核心线程数后,往任务队列放
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))//再次检查,如果线程池不是RUNNING状态,移除任务
            reject(command);
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    else if (!addWorker(command, false))//队列满了,添加非核心线程数
        reject(command);
}

addWorker

private boolean addWorker(Runnable firstTask, boolean core) {
    retry:
    //cas给 workCount 加一
    for (;;) {
        int c = ctl.get();
        //拿到线程池当前状态 runState
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN &&
            //队列不为空才能补充线程
            ! (rs == SHUTDOWN &&     //不接受外部的任务,但会执行队列中的任务
               firstTask == null &&  //是否是补充非核心线程
               ! workQueue.isEmpty()))//队列是否为空
            return false;

        for (;;) {
            int wc = workerCountOf(c);
            if (wc >= CAPACITY ||
                wc >= (core ? corePoolSize : maximumPoolSize))
                return false;
            if (compareAndIncrementWorkerCount(c))//CAS的加一操作
                break retry;
            c = ctl.get();  // Re-read ctl  失败之后重试
            if (runStateOf(c) != rs)
                continue retry;
            // else CAS failed due to workerCount change; retry inner loop
        }
    }

    boolean workerStarted = false;
    boolean workerAdded = false;
    Worker w = null;
    try {
        //新增一个 Worker
        w = new Worker(firstTask);
        final Thread t = w.thread;
        if (t != null) {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();//加锁,往workers里添加work, workers装着所有的Worker 类型是HashSet

            try {
                // Recheck while holding lock.
                // Back out on ThreadFactory failure or if
                // shut down before lock acquired.
                int rs = runStateOf(ctl.get());

                if (rs < SHUTDOWN ||
                    (rs == SHUTDOWN && firstTask == null)) {
                    if (t.isAlive()) // precheck that t is startable
                        throw new IllegalThreadStateException();
                    workers.add(w);
                    int s = workers.size();
                    if (s > largestPoolSize)
                        largestPoolSize = s;
                    workerAdded = true;
                }
            } finally {
                mainLock.unlock();
            }
            if (workerAdded) {//添加成功,启动Worker中thread对应的run方法
                t.start();
                workerStarted = true;
            }
        }
    } finally {
        if (! workerStarted)//添加失败,移除Worker,线程数减一
            addWorkerFailed(w);
    }
    return workerStarted;
}
  • Worker
Worker(Runnable firstTask) {
    setState(-1); // inhibit interrupts until runWorker
    this.firstTask = firstTask;
    this.thread = getThreadFactory().newThread(this);
}