乐趣区

关于java:JUC线程池ThreadPoolExecutor

样例及原理

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 原理

线程池工作流程

  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;


// -- 最高 4 位标识状态,其余低位表线程个数
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. 获取工作线程数办法,取低 28 位
//      入参 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. 获取状态的办法,取高 4 位
//      入参 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;}
    }
}
退出移动版