1. 程式人生 > >執行緒池ThreadPoolExecutor分析

執行緒池ThreadPoolExecutor分析

執行緒池,執行緒池是什麼,說到底,執行緒池是處理多執行緒的一種形式,管理執行緒的建立,任務的執行,避免了無限建立新的執行緒帶來的資源消耗,能夠提高應用的效能。很多相關操作都是離不開的執行緒池的,比如android應用中網路請求的封裝。這篇部落格要解決的問題是:

1.執行緒池的工作原理及過程。

要分析執行緒池的工作原理及過程,還是要從它的原始碼實現入手,首先是執行緒是構造方法,何謂構造方法,構造方法就是對成員變數進行初始化,在這裡,我們可以看到它的構造方法:

/**
     * Creates a new {@code ThreadPoolExecutor} with the given initial
     * parameters.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @param maximumPoolSize the maximum number of threads to allow in the
     *        pool
     * @param keepAliveTime when the number of threads is greater than
     *        the core, this is the maximum time that excess idle threads
     *        will wait for new tasks before terminating.
     * @param unit the time unit for the {@code keepAliveTime} argument
     * @param workQueue the queue to use for holding tasks before they are
     *        executed.  This queue will hold only the {@code Runnable}
     *        tasks submitted by the {@code execute} method.
     * @param threadFactory the factory to use when the executor
     *        creates a new thread
     * @param handler the handler to use when execution is blocked
     *        because the thread bounds and queue capacities are reached
     * @throws IllegalArgumentException if one of the following holds:<br>
     *         {@code corePoolSize < 0}<br>
     *         {@code keepAliveTime < 0}<br>
     *         {@code maximumPoolSize <= 0}<br>
     *         {@code maximumPoolSize < corePoolSize}
     * @throws NullPointerException if {@code workQueue}
     *         or {@code threadFactory} or {@code handler} is null
     */
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler) {
        if (corePoolSize < 0 ||
            maximumPoolSize <= 0 ||
            maximumPoolSize < corePoolSize ||
            keepAliveTime < 0)
            throw new IllegalArgumentException();
        if (workQueue == null || threadFactory == null || handler == null)
            throw new NullPointerException();
        this.corePoolSize = corePoolSize;
        this.maximumPoolSize = maximumPoolSize;
        this.workQueue = workQueue;
        this.keepAliveTime = unit.toNanos(keepAliveTime);
        this.threadFactory = threadFactory;
        this.handler = handler;
    }
第一個引數,corePoolSize核心執行緒的數量;maximumPoolSize最大執行緒數量;keepAliveTime和 TimeUnit非核心執行緒閒置時間,超過這個設定時間將會被終止,TimeUnit含有多種靜態成員變數作為單位,如seconds;BlockingQueue任務阻塞佇列,當核心執行緒建立數量達到最大值時,任務首先會加入到阻塞佇列,等待執行;ThreadFactory 執行緒構造工廠,常用的有DefaultThreadFactory,我們也可以重寫它的newThread方法,實現這個類;RejectedExecutionHandler,當任務被拒絕新增時,將會交給這個類處理。好了,構造的過程,就是這麼簡單,就是初始化一些成員變數。

分析的時候,從關鍵點著手,這裡分析是從execute()方法入手的:

 /**
     * Executes the given task sometime in the future.  The task
     * may execute in a new thread or in an existing pooled thread.
     *
     * If the task cannot be submitted for execution, either because this
     * executor has been shutdown or because its capacity has been reached,
     * the task is handled by the current {@code RejectedExecutionHandler}.
     *
     * @param command the task to execute
     * @throws RejectedExecutionException at discretion of
     *         {@code RejectedExecutionHandler}, if the task
     *         cannot be accepted for execution
     * @throws NullPointerException if {@code command} is null
     */
    public void execute(Runnable command) {
        if (command == null)
            throw new NullPointerException();
        /*
         * Proceed in 3 steps:
         *
         * 1. If fewer than corePoolSize threads are running, try to
         * start a new thread with the given command as its first
         * task.  The call to addWorker atomically checks runState and
         * workerCount, and so prevents false alarms that would add
         * threads when it shouldn't, by returning false.
         *
         * 2. If a task can be successfully queued, then we still need
         * to double-check whether we should have added a thread
         * (because existing ones died since last checking) or that
         * the pool shut down since entry into this method. So we
         * recheck state and if necessary roll back the enqueuing if
         * stopped, or start a new thread if there are none.
         *
         * 3. If we cannot queue task, then we try to add a new
         * thread.  If it fails, we know we are shut down or saturated
         * and so reject the task.
         */
        int c = ctl.get();
        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);
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        else if (!addWorker(command, false))
            reject(command);
    }
上面execute的方法,傳入的是一個Runnable,這個方法就是我們需要執行的任務。下面我們分析execute是怎麼執行這個任務的,也就是execute執行的過程:

        1.如果執行緒池中執行緒的數量小於核心執行緒數目,則啟動一個新的執行緒處理這個任務。

        2.如果核心執行緒處於非空閒狀態,則將任務插入到阻塞佇列中,當有執行緒空閒時,會自動取出任務執行。

        3.如果阻塞佇列任務已經滿了,並且當前執行緒小於最大執行緒數目,則啟動新的執行緒,執行任務,如果超過了最大執行緒數,則拒絕接受新的任務。

上面是整個程式碼的過程,現在我們隊程式碼進行分析
        

 if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true))
                return;
workerCountOf(c)表示的是當前執行緒的數量,如果這個數量小於corePoolSize,則呼叫addWorker(command,true)方法,如果addWorker執行成功,返回true,表示任務執行完成。下面我們看addWorker方法:
 private boolean addWorker(Runnable firstTask, boolean core) {
        retry:
        for (;;) {
            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);
                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;
                // 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 {
                    // 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();
                }
                if (workerAdded) {
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }
addWorker方法比較長,我們分為兩塊,第一塊的for迴圈,第二塊try...。第一塊,for迴圈,主要是判斷當前是否可以執行任務,如果可以,則進行下面的try,通過的條件,可以分析出來,是當前執行緒小於核心執行緒,或者當前阻塞佇列已滿,執行緒數小於最大執行緒數量,滿足這兩個中的條件,才能往下走。       try裡面通過當前的引數,新建了一個Worker,這個Worker實現了Runable介面,Worker裡面通過ThreadFactory構建了一個Thread來執行這個任務,程式碼的後面,呼叫了t.start(),實際上,呼叫的是,Worker實現Runable的run方法,run方法呼叫的又是runWorker(),我們看runWorker方法
 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 pool is stopping, ensure thread is interrupted;
                // if not, ensure thread is not interrupted.  This
                // requires a recheck in second case to deal with
                // shutdownNow race while clearing interrupt
                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 {
            processWorkerExit(w, completedAbruptly);
        }
    }

首先我們要知道,整個runWorker方法是在Thread的執行緒中執行的。runWorker中,while迴圈中,加鎖,第一次task不為空,執行這個firstTask,當task.run()執行完,解鎖,然後呼叫getTask(),getTask是從阻塞佇列中取出任務來執行,因此,這裡,我們得出結論,當執行緒完成一個任務時,會從阻塞佇列裡取出任務來執行。        while迴圈的條件是,task 不為空,或者getTask不為空,如果task為空,並且getTask也為空,就跳出迴圈,但是,先請看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())) {
                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;
            }
        }
    }

這個方法的主要作用是從佇列中取出一個任務執行,然而,我們仔細分析,如果allowCoreThreadTimeOut為true(也就是說允許核心執行緒超時),或者當前執行緒是非核心執行緒,那麼timed=true,這時候,進入if語句判斷,wc>maximuPoolsize,這個一般不成立,直接看timed&&timeOut,timed=true,timeOut為false,直接進入try,最後timeOut=true,當後面迴圈時,如果佇列的任務為空,就會執行到compareAndDecrementWorkerCount(c)減少一個執行緒數量,然後返回null,執行緒也就終止執行了;但是如果allowCoreThreadTimeOut=false,就會直接呼叫workQueue.take(),直接取出一個Runnable,如果runnable為空,就將一直迴圈,執行緒阻塞在這裡,也就是核心執行緒處於空閒狀態。這裡得出新的結論,如果核心執行緒沒有允許超時,那麼它將一直處於空閒狀態,不會被回收。

我們再次回到execute方法,第二部分

 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);
        }
如果當前執行緒池處於執行狀態,並且這個任務能插入到佇列中(因為這裡執行緒數目已經時等於核心執行緒數了,因此插入到佇列中,等待執行),第二次判斷,如果當前執行緒池不處於執行狀態,那麼移除這個任務,呼叫reject方法處理;如果當前執行緒池的執行緒數量為0,addWorker(),傳入null和false,也就是說,不新增新任務,並且時啟動一個非核心執行緒,這個核心執行緒會通過getTask()方法取出任務執行,這個和上面分析的過程一樣。

第三部分

 else if (!addWorker(command, false))
            reject(command);
先啟動一個非核心執行緒執行任務,如果非核心執行緒達到了最大執行緒數,才會拒絕執行任務。


最後的結論就是:

1.如果執行緒池中執行緒的數量小於核心執行緒數目,則啟動一個新的執行緒處理這個任務。

2.如果核心執行緒處於非空閒狀態,則將任務插入到阻塞佇列中,當有執行緒空閒時,會自動取出任務執行。

3.如果阻塞佇列任務已經滿了,並且當前執行緒小於最大執行緒數目,則啟動新的執行緒,執行任務,如果超過了最大執行緒數,則拒絕接受新的任務。

如果核心執行緒沒有設定為允許超時,那麼核心執行緒會一直存在,即時等待執行任務。