java并发编程学习之线程池-ThreadPoolExecutor(三)

ThreadPoolExecutor

ThreadPoolExecutor是所有线程池实现的父类,我们先看看构造函数

构造参数

  • corePoolSize:线程核心数
  • maximumPoolSize:最大线程数
  • keepAliveTime:线程空闲后,存活的时间,只有线程数大于corePoolSize的时候生效
  • unit:存活时间的单位
  • workQueue:任务的阻塞队列
  • threadFactory:创建线程的工程,给线程起名字
  • handler:当线程池满了,选择新加入的任务应该使用什么策略,比如抛异常、丢弃当前任务、丢弃阻塞队列的最老任务等,也可以自定义。

流程

  1. 判断是否超过线程核心数corePoolSize,没超过创建线程
  2. 超过线程核心数,则判断队列是否已满,没有满,放入队列
  3. 队列也满了,判断是否超过maximumPoolSize,没有就创建线程
  4. 超过了,根据策略执行

java并发编程学习之线程池-ThreadPoolExecutor(三)_第1张图片

源码解析

//32为,前3位作为线程池的状态,后三位是线程数
private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
private static final int COUNT_BITS = Integer.SIZE - 3;//28
private static final int CAPACITY   = (1 << COUNT_BITS) - 1;00011111 11111111 11111111 11111110
//-1的二进制是11111111 11111111 11111111 11111111
private static final int RUNNING    = -1 << COUNT_BITS;//-1如上,左移28位后,就是111000000 00000000 00000000 00000000
private static final int SHUTDOWN   =  0 << COUNT_BITS;//0左移28位,还是0,00000000 00000000 00000000 00000000
private static final int STOP       =  1 << COUNT_BITS;//00100000 00000000 00000000 00000000
private static final int TIDYING    =  2 << COUNT_BITS;//01000000 00000000 00000000 00000000
private static final int TERMINATED =  3 << COUNT_BITS;//01100000 00000000 00000000 00000000
private static int runStateOf(int c)     { return c & ~CAPACITY; }//~CAPACITY为11100000000000000000000000000000,与完就是线程的状态
private static int workerCountOf(int c)  { return c & CAPACITY; }//与完,是线程的数量
private static int ctlOf(int rs, int wc) { return rs | wc; }
private static boolean isRunning(int c) {
    return c < SHUTDOWN;//小于0,说明是RUNNING,RUNNING=-1
}

execute方法

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    int c = ctl.get();
    if (workerCountOf(c) < corePoolSize) {//如果线程数少于线程核心数
        if (addWorker(command, true))//增加任务成功,返回true,没成功,继续往下
            return;
        c = ctl.get();
    }
    //判断队列
    if (isRunning(c) && workQueue.offer(command)) {//如果线程池还在跑,并且可以插入队列
        int recheck = ctl.get();
        if (! isRunning(recheck) && remove(command))//线程池不是运行状态,就移除刚刚插入的任务
            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) {//core为true,使用corePoolSize判断,否则使用maximumPoolSize
    retry:
    for (;;) {
        int c = ctl.get();
        int rs = runStateOf(c);//获取当前线程状态

        // Check if queue empty only if necessary.
        if (rs >= SHUTDOWN && // 就是STOP、TIDYING、TERMINATED,此时不让任务进来
            ! (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))//返回true,说明成功了,跳出retry循环
                break retry;
            //失败了,说明被其他符号条件的线程占了,就再判断线程状态是否跟之前一样,不一样重新获取,跳到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 {
        w = new Worker(firstTask);
        final Thread t = w.thread;
        if (t != null) {
            final ReentrantLock mainLock = this.mainLock;
            mainLock.lock();//获取锁
            try {
                int rs = runStateOf(ctl.get());//获取线程池的状态

                if (rs < SHUTDOWN ||
                    (rs == SHUTDOWN && firstTask == null)) {
                    if (t.isAlive()) // 没通过start来启动run的
                        throw new IllegalThreadStateException();
                    workers.add(w);//加点hashset
                    int s = workers.size();
                    if (s > largestPoolSize)
                        largestPoolSize = s;//更新当前最大值
                    workerAdded = true;//增加成功
                }
            } finally {
                mainLock.unlock();
            }
            if (workerAdded) {
                t.start();//启动线程
                workerStarted = true;//启动成功
            }
        }
    } finally {
        if (! workerStarted)
            addWorkerFailed(w);//失败,线程数-1,从hashset移除,并尝试Terminate
    }
    return workerStarted;
}

runWorker方法

上面执行 t.start();的时候,就会通过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) {//任务不为空或者获取的任务也不为空
            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 {
                    task.run();//调用run方法,这里没有通过start,也就是说没有启动新线程
                } 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++;//完成任务数加1
                w.unlock();//释放
            }
        }
        completedAbruptly = false;
    } finally {
        processWorkerExit(w, completedAbruptly);//移除w,在task为空的时候,比如线程池状态停止或者启动的线程太多
    }
}

getTask方法
当Worker第一次启动的时候,调用run方法,后面就一直从队列里获取任务

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();//线程数量-1
            return null;
        }

        int wc = workerCountOf(c);//线程数
        //allowCoreThreadTimeOut为true,说明线程数要根据是否超过核心线程数判断keepAliveTime
        boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;//是否超过核心线程数

        if ((wc > maximumPoolSize || (timed && timedOut))//超过了最大线程数
            && (wc > 1 || workQueue.isEmpty())) {
            if (compareAndDecrementWorkerCount(c))//线程数-1
                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;
        }
    }
}

你可能感兴趣的:(java,线程池,源码分析)