java併發編程學習之線程池-ThreadPoolExecutor(三)

ThreadPoolExecutor

ThreadPoolExecutor是全部線程池實現的父類,咱們先看看構造函數函數

構造參數

  • corePoolSize:線程核心數
  • maximumPoolSize:最大線程數
  • keepAliveTime:線程空閒後,存活的時間,只有線程數大於corePoolSize的時候生效
  • unit:存活時間的單位
  • workQueue:任務的阻塞隊列
  • threadFactory:建立線程的工程,給線程起名字
  • handler:當線程池滿了,選擇新加入的任務應該使用什麼策略,好比拋異常、丟棄當前任務、丟棄阻塞隊列的最老任務等,也能夠自定義。

流程

  1. 判斷是否超過線程核心數corePoolSize,沒超過建立線程
  2. 超過線程核心數,則判斷隊列是否已滿,沒有滿,放入隊列
  3. 隊列也滿了,判斷是否超過maximumPoolSize,沒有就建立線程
  4. 超過了,根據策略執行

clipboard.png

源碼解析

//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方法調用下面的方法oop

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方法,後面就一直從隊列裏獲取任務this

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;
        }
    }
}
相關文章
相關標籤/搜索