4

【JUC】线程池ThreadPoolExecutor

 3 years ago
source link: https://segmentfault.com/a/1190000041362548
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

样例及原理

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;


// -- 最高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;
        }
    }
}

Recommend

  • 72

    版权声明:本文为博主原创文章,未经博主允许不得转载 源码:github.com/AnliaLee 大家要是看到有错误的地方或者有啥好的建议,欢迎留言评论 前言 本篇博客我们将开始探索由上一章引出的线程池(ThreadPoolExecutor)的知识。由于内含

  • 78
    • www.linkedkeeper.com 7 years ago
    • Cache

    线程池ThreadPoolExecutor源码解析

  • 50

  • 88

    以下所有内容以及源码分析都是基于JDK1.8的,请知悉。我写博客就真的比较没有顺序了,这可能跟我的学习方式有关,我自己也觉得这样挺不好的,但是没办法说服自己去改变,所以也只能这样想到什么学什么了。池化技术真的是一门在我看来非常牛逼的技术,因为它做到了...

  • 66

    【编者的话】在Java中,使用线程池来异步执行一些耗时任务是非常常见的操作。最初我们一般都是直接使用new Thread().start的方式,但我们知道,线程的创建和销毁都会耗费大量的资源,关于线程可以参考之前的一篇博客《

  • 66

    线程池介绍在web开发中,服务器需要接受并处理请求,所以会为一个请求来分配一个线程来进行处理。如果每次请求都新创建一个线程的话实现起来非常简便,但是存在一个问题:如果并发的请求数量非常多,但每个线程执行的时间很短,这样就会频繁的创建和销毁线程,如此...

  • 64

    线程池介绍 在web开发中,服务器需要接受并处理请求,所以会为一个请求来分配一个线程来进行处理。如果每次请求都新创建一个线程的话实现起来非常简便,但是存在一个问题: 如果并发的请求数量非常多,但每个线程执行的...

  • 63
    • monkeysayhi.github.io 6 years ago
    • Cache

    线程池ThreadPoolExecutor总结

    之前在 ...

  • 10
    • huyan.couplecoders.tech 3 years ago
    • Cache

    (juc系列)threadpoolexecutor源码学习

    (juc系列)threadpoolexecutor源码学习 - 呼延十的博客 | HuYan Blog本文源码基于: JDK13 其实早在19年,就简单的写过ThreadPoolExecutor. 但是只涉及到了其中两个参数,理解也不深刻,今天重新看一下代码。 这个类是Java中常...

  • 9

    JUC系列(一)详解线程池ThreadPoolExecutor一、继承关系&构建参数跟其他池化技术一样,线程池的目的也是为了重复利用资源,节省开销,提升程序运行速度,java提供的线程池位于juc包中,这是它的继承树:

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK