头图

样例及原理

ThreadPoolExecutor executor = new ThreadPoolExecutor(
        2, // 核心线程数
        4,  // 最大线程数
        5, TimeUnit.SECONDS,    // 最大线程的回收时间
        new ArrayBlockingQueue<>(999),  // 阻塞队列
        (Runnable r, ThreadPoolExecutor executor)->{
            // 自定义拒绝策略
        }
);

@Test
public void test(){
    executor.execute(()->{
        // 交给线程池执行的任务
    });
    Future<String> future = executor.submit(()->{
        // 交给线程池执行的有返回值的任务
        return "";
    });
}

execute原理

image.png

线程池工作流程

  1. 工作线程数 < 核心线程数,创建线程

线程一直处于while循环中(不被释放),首次直接执行任务,之后以take方式获取阻塞队列任务

  1. 工作线程数 >= 核心线程数,offer方式将任务加入阻塞队列
  • offer成功:什么都不用做,等待队列任务被消费即可
  • offer失败:创建最大线程;
    最大线程会采用poll+超时时间的方式获取阻塞队列任务;超时未获取到任务,会跳出循环最大线程释放

超级变量ctl:记录线程池状态及个数

// -- 线程池生命周期的各个状态(COUNT_BITS=29)
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;


// -- 最高3位标识状态,其余低位表线程个数
private final AtomicInteger ctl = new AtomicInteger(
                                            //  (RUNNING | 0)
                                            // 初始值:1110 0000 0000 0000 0000 0000 0000 0000
                                            ctlOf(RUNNING, 0));


// 0001 1111 1111 1111 1111 1111 1111 1111
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

// == 1.获取工作线程数方法,取低29位
//      入参c:ctl.get()
//      以ctl初始值为例:
//            1110 0000 0000 0000 0000 0000 0000 0000 
//            0001 1111 1111 1111 1111 1111 1111 1111 (CAPACITY)
//            &操作结果是0
private static int workerCountOf(int c)  { return c & CAPACITY; }

// == 2.获取状态的方法,取高3位
//      入参c:ctl.get()
//      以ctl初始值为例:
//            1110 0000 0000 0000 0000 0000 0000 0000 
//            1110 0000 0000 0000 0000 0000 0000 0000 (~CAPACITY)
//            &操作结果是RUNNING
private static int runStateOf(int c)     { return c & ~CAPACITY; }

线程池接收任务的核心处理

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();

    int c = ctl.get();
    // == 1.小于核心线程数,增加工作线程
    if (workerCountOf(c) < corePoolSize) {
        if (addWorker(command, true))
            return;
        c = ctl.get();
    }
    
    // == 2.线程池正在运行,且正常添加任务
    if (isRunning(c) && workQueue.offer(command)) {
        int recheck = ctl.get();
        // -- 2.1 线程池处于非运行状态,且任务能从队列中移除:则执行拒绝策略
        if (! isRunning(recheck) && remove(command))
            reject(command);
        // -- 2.2 无工作线程,直接创建无任务线程
        else if (workerCountOf(recheck) == 0)
            addWorker(null, false);
    }
    
    // == 3.最大线程创建失败:则执行拒绝策略
    else if (!addWorker(command, false))
        reject(command);
}

新增线程做了哪些操作?

private boolean addWorker(Runnable firstTask, 
        // -- true:增加核心线程数
        // -- false:增加最大线程数
        boolean core) {
    // == 1.判定是否允许新增线程,如果允许则增加线程计数
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        // 线程池状态判定
        if (rs >= SHUTDOWN &&
            ! (rs == SHUTDOWN &&
               firstTask == null &&
               ! workQueue.isEmpty()))
            return false;

        for (;;) {
            int wc = workerCountOf(c);
            // ## 线程数判定:
            //    大于线程允许的最大值,或大于线程参数(根据core,判定核心线程数或最大线程数)
            //    则返回false
            if (wc >= CAPACITY 
                    || wc >= (core ? corePoolSize : maximumPoolSize)){
                return false;
            }
            // ## 增加线程计数,成功后跳出外层循环
            if (compareAndIncrementWorkerCount(c))
                break retry;
            c = ctl.get();  // Re-read ctl
            if (runStateOf(c) != rs)
                continue retry;
        }
    }

    // == 2.新增线程,并让线程执行任务
    boolean workerStarted = false;
    boolean workerAdded = false;
    Worker w = null;
    try {
        // ## 2.1 创建worker,构造函数中创建线程
        w = new Worker(firstTask);
        final Thread t = w.thread;
        if (t != null) {
            final ReentrantLock mainLock = this.mainLock;
            
            //  ## 2.2 加锁,向工作线程集合中加入新增的线程
            mainLock.lock();
            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();
            }
            // 2.2步骤结束
            
            // ## 2.3 任务开始执行:新增的工作线程执行start方法
            if (workerAdded) {
                t.start();
                workerStarted = true;
            }
        }
    } finally {
        if (! workerStarted)
            addWorkerFailed(w);
    }
    return workerStarted;
}

工作线程如何工作?

public void run() {
    runWorker(this);
}

final void runWorker(Worker w) {
    Thread wt = Thread.currentThread();
    Runnable task = w.firstTask;
    w.firstTask = null;
    w.unlock(); // allow interrupts
    boolean completedAbruptly = true;
    try {
        // ## 循环中
        while (task != null 
                // == 1.take方式从阻塞队列里获取任务,如果无任务则阻塞
                //    未获取到任务,将跳出循环——意味着本线程释放
                || (task = getTask()) != null) {
            
            // -- 加锁执行任务(Worker继承了AQS)
            w.lock();
            
            if ((runStateAtLeast(ctl.get(), STOP) ||
                 (Thread.interrupted() &&
                  runStateAtLeast(ctl.get(), STOP))) &&
                !wt.isInterrupted())
                wt.interrupt();
            
            try {
                // 任务执行前的函数,需自定义实现
                beforeExecute(wt, task);
                Throwable thrown = null;
                try {
                    // == 2.从阻塞队列里获取任务,如果有任务则当前线程执行
                    task.run();
                } catch (RuntimeException x) {
                    thrown = x; throw x;
                } catch (Error x) {
                    thrown = x; throw x;
                } catch (Throwable x) {
                    thrown = x; throw new Error(x);
                } finally {
                    // 任务执行后的函数,需自定义实现
                    afterExecute(task, thrown);
                }
            } finally {
                task = null;
                w.completedTasks++;
                w.unlock();
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);
    }
}

具体的任务获取方法

private Runnable getTask() {
    boolean timedOut = false; // Did the last poll() time out?

    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);

        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN && (rs >= STOP || workQueue.isEmpty())) {
            decrementWorkerCount();
            return null;
        }

        int wc = workerCountOf(c);

        // ## 允许核心线程执行任务超时,或者线程数已经超过了核心线程数(已经是最大线程开始执行任务)
        boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;

        if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
            // 工作线程数递减,比如超时获取任务情况
            if (compareAndDecrementWorkerCount(c))
                return null;
            continue;
        }

        try {
            // ## 
            // -- 有超时设置,采用`poll+超时`的方式从阻塞队列获取任务
            //    如:最大线程超时未获取到任务,将返回null
            
            // -- 无超时设置,采用`take`的方式从阻塞队列获取任务(如果无任务,则阻塞)
            Runnable r = timed ?
                workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                workQueue.take();
            if (r != null)
                return r;
            timedOut = true;
        } catch (InterruptedException retry) {
            timedOut = false;
        }
    }
}

青鱼
268 声望25 粉丝

山就在那里,每走一步就近一些