ThreadPoolExecutor 源码解析

重要属性

    //ctl是一个原子整数,包含两个概念字段workerCount,指示线程的有效运行状态数,指示是否正在运行、正在关闭等,前29位标识线程数量,后3位标识状态
    //workerCount是允许启动和不允许停止的工人数。该值可能与实际线程的实际数量不同,例如当线程工厂在被请求时无法创建线程时,以及退出线程在终止之前仍在执行簿记。用户可见池大小报告为工作集的当前大小。
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    
    //主要是对worker集合进行锁定,保证退出时的中断
    private final ReentrantLock mainLock = new ReentrantLock();
    
    //存放工作线程的地方
    private final HashSet<Worker> workers = new HashSet<Worker>();

线程池的运行状态

RUNNING

接受新任务并处理排队的任务

SHUTDOWN

不接受新任务,但处理排队的任务

STOP

不接受新任务,不处理排队的任务,并且中断正在进行的任务

TIDYING

所有任务都已终止,workerCount为零,转换为状态整理的线程,将运行terminated()钩子方法

TERMINATED

TERMINATED()已完成

这些值之间的数字顺序很重要,以便进行有序比较。运行状态随时间单调地增加,但不必命中每个状态。过程是:
1.RUNNING -> SHUTDOWN 调用shutdown()时,可能隐式地在finalize()中
2.(RUNNING or SHUTDOWN) -> STOP 调用shutdownNow的时候
3.SHUTDOWN -> TIDYING 队列和线程池为空的时候
4.STOP -> TIDYING 当线程池为空的时候
5.TIDYING -> TERMINATED 当terminated()钩子方法完成时

等待awaitTermination()的线程将在状态达到TERMINATED时返回。

构造函数

    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue) {
        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
             Executors.defaultThreadFactory(), defaultHandler);
    }

execute方法

public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        int c = ctl.get();
        //workerCountOf获取线程数量,判断是否小于核心线程数
        if (workerCountOf(c) < corePoolSize) {
            //创建核心线程
            if (addWorker(command, true))
                return;
            c = ctl.get();
        }
        //核心线程满了就塞到阻塞队列里
        if (isRunning(c) && workQueue.offer(command)) {
            //再检查一遍如果不是运行状态就拒绝
            int recheck = ctl.get();
            if (! isRunning(recheck) && remove(command))
                reject(command);
            //如果工作线程是0,新增非核心线程池
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        
        //阻塞队列也塞不下了执行拒绝策略,就创建非核心线程,如果非核心线程创建失败就执行拒绝策略
        else if (!addWorker(command, false))
            reject(command);
    }
    
    //新建线程并添加到核心线程池中
    //1.先增加数量2.添加到set 3.再运行方法
    private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            //rs线程的运行状态
            int c = ctl.get();
            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);
                //数量校验,如果没有通过返回false
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                
                //CAS增加workCount
                if (compareAndIncrementWorkerCount(c))
                    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 {
            //新建work
            w = new Worker(firstTask);
            final Thread t = w.thread;
            if (t != null) {
                final ReentrantLock mainLock = this.mainLock;
                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();
                }
                //worker添加成功开始运行
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }

Worker#run方法

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 || (task = getTask()) != null) {
                //锁住自己 调用AQS的acquire(1)
                w.lock();
                //如果线程池的状态是STOPPING,确保线程已经被中断,如果没有中断,确保线程没有中断
                if ((runStateAtLeast(ctl.get(), STOP) ||
                     (Thread.interrupted() &&
                      runStateAtLeast(ctl.get(), STOP))) &&
                    !wt.isInterrupted())
                    wt.interrupt();
                try {
                    beforeExecute(wt, task);
                    Throwable thrown = null;
                    try {
                        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 {
            //把worker从线程池踢出
            processWorkerExit(w, completedAbruptly);
        }
    }

woker##getTask 工作线程拉取任务

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())) {
                //woker-1
                decrementWorkerCount();
                return null;
            }
            int wc = workerCountOf(c);
            // Are workers subject to culling?
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }
            try {
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

拒绝策略

https://juejin.im/post/5e33dd725188254c3806ebf5

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!
0 条回复 A 作者 M 管理员
    所有的伟大,都源于一个勇敢的开始!
欢迎您,新朋友,感谢参与互动!欢迎您 {{author}},您在本站有{{commentsCount}}条评论