Java線程池原理淺析

一睦番、線程池工廠Executors

我們平時(shí)在使用線程池的時(shí)候一般都是通過Executors的newXxxxxPool()靜態(tài)方法來獲得不同功能的線程池對(duì)象。我們來看一下這些方法都是怎么創(chuàng)建線程池的:

     /**
      * 固定線程數(shù)的線程池
      */
    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>(),
                                      threadFactory);
    }
     /**
      * 只有一個(gè)線程的線程池
      */
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }
     /**
      * 可變大小線程池
      */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
     /**
      *定時(shí)執(zhí)行的線程池
      */
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }

我們可以看到這newFixedThreadPool()、newSingleThreadExecutor()凉袱、newCachedThreadPool()都是創(chuàng)建了一個(gè)ThreadPoolExecutor對(duì)象闷板,而newScheduledThreadPool()則是創(chuàng)建了一個(gè)ScheduledThreadPoolExecutor對(duì)象,其實(shí)ScheduledThreadPoolExecutor也是繼承了ThreadPoolExecutor這個(gè)類蛹头,通過在ThreadPoolExecutor上擴(kuò)展實(shí)現(xiàn)了定時(shí)執(zhí)行線程的功能顿肺。

ThreadPoolExecutor

我們先來看一下ThreadPoolExecutor的構(gòu)造方法:

    /**
     * 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:線程池里最小線程數(shù)
maximumPoolSize:線程池里最大線程數(shù)
keepAliveTime:空閑線程存活的時(shí)間,也就是線程池的線程數(shù)超過corePoolSize后掘而,空閑線程可以存活的時(shí)間挟冠,超過這個(gè)時(shí)間就會(huì)被銷毀。
unit: keepAliveTime的單位
workQueue:用來存放等待任務(wù)的隊(duì)列袍睡。這個(gè)隊(duì)列是個(gè)阻塞隊(duì)列
threadFactory:用來產(chǎn)生線程池里的線程的工廠
handler:當(dāng)任務(wù)超過最大允許的任務(wù)數(shù)量后知染,新來任務(wù)的拒絕策略。
知道了上面幾個(gè)參數(shù)斑胜,我們對(duì)ThreadPoolExecutor應(yīng)該有所了解控淡,對(duì)Executors產(chǎn)生的不同功能的線程池也應(yīng)該有所了解嫌吠。我們接下來討論一下ThreadPoolExecutor實(shí)現(xiàn)線程池的原理。
首先從提交任務(wù)的方法開始:

    /**
     * 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}.
     *執(zhí)行給定的任務(wù)掺炭,這個(gè)任務(wù)可能在一個(gè)新的線程里執(zhí)行辫诅,也可能在一個(gè)已經(jīng)存在的線程里執(zhí)行
     *如果任務(wù)不能被提交,不管是因?yàn)閑xecutor被shutdown還是因?yàn)槿萘康竭_(dá)界限涧狮,任務(wù)都會(huì)被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);
    }

首先看到這一行代碼:int c = ctl.get(); ctl是什么呢?我們來看一下關(guān)于ctl的定義:

    /**
     * The main pool control state, ctl, is an atomic integer packing
     * two conceptual fields
     *   workerCount, indicating the effective number of threads
     *   runState,    indicating whether running, shutting down etc
     *
     * In order to pack them into one int, we limit workerCount to
     * (2^29)-1 (about 500 million) threads rather than (2^31)-1 (2
     * billion) otherwise representable. If this is ever an issue in
     * the future, the variable can be changed to be an AtomicLong,
     * and the shift/mask constants below adjusted. But until the need
     * arises, this code is a bit faster and simpler using an int.
     *
     * The workerCount is the number of workers that have been
     * permitted to start and not permitted to stop.  The value may be
     * transiently different from the actual number of live threads,
     * for example when a ThreadFactory fails to create a thread when
     * asked, and when exiting threads are still performing
     * bookkeeping before terminating. The user-visible pool size is
     * reported as the current size of the workers set.
     *
     * The runState provides the main lifecycle control, taking on values:
     *
     *   RUNNING:  Accept new tasks and process queued tasks
     *   SHUTDOWN: Don't accept new tasks, but process queued tasks
     *   STOP:     Don't accept new tasks, don't process queued tasks,
     *             and interrupt in-progress tasks
     *   TIDYING:  All tasks have terminated, workerCount is zero,
     *             the thread transitioning to state TIDYING
     *             will run the terminated() hook method
     *   TERMINATED: terminated() has completed
     *
     * The numerical order among these values matters, to allow
     * ordered comparisons. The runState monotonically increases over
     * time, but need not hit each state. The transitions are:
     *
     * RUNNING -> SHUTDOWN
     *    On invocation of shutdown(), perhaps implicitly in finalize()
     * (RUNNING or SHUTDOWN) -> STOP
     *    On invocation of shutdownNow()
     * SHUTDOWN -> TIDYING
     *    When both queue and pool are empty
     * STOP -> TIDYING
     *    When pool is empty
     * TIDYING -> TERMINATED
     *    When the terminated() hook method has completed
     *
     * Threads waiting in awaitTermination() will return when the
     * state reaches TERMINATED.
     *
     * Detecting the transition from SHUTDOWN to TIDYING is less
     * straightforward than you'd like because the queue may become
     * empty after non-empty and vice versa during SHUTDOWN state, but
     * we can only terminate if, after seeing that it is empty, we see
     * that workerCount is 0 (which sometimes entails a recheck -- see
     * below).
     */
    private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
    private static final int COUNT_BITS = Integer.SIZE - 3;
    private static final int CAPACITY   = (1 << COUNT_BITS) - 1;

    // runState is stored in the high-order bits
    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;

    // Packing and unpacking ctl
    private static int runStateOf(int c)     { return c & ~CAPACITY; }
    private static int workerCountOf(int c)  { return c & CAPACITY; }
    private static int ctlOf(int rs, int wc) { return rs | wc; }

注釋已經(jīng)很清楚告訴我們ctl是workerCount和runSate的結(jié)合者冤。我們可以看到肤视,線程池的容量是CAPACITY(線程池中允許的最大線程數(shù)是CAPACITY),也就是2的Integer.SIZE-3次方減一涉枫。ctl用低29位表示線程池中的線程數(shù)邢滑,用剩下的高3位表示線程池的運(yùn)行狀態(tài)。這一點(diǎn)大家要理解清楚愿汰。這下面三個(gè)方法是對(duì)ctl的操作

    private static int runStateOf(int c)     { return c & ~CAPACITY; }  //獲取高三位困后,也就是線程池的運(yùn)行狀態(tài)
    private static int workerCountOf(int c)  { return c & CAPACITY; }  //獲取低29位,也就是線程池線程的數(shù)量
    private static int ctlOf(int rs, int wc) { return rs | wc; }  //生成ctl

理解了這個(gè)之后衬廷,我們繼續(xù)回到execute方法摇予,當(dāng)一個(gè)任務(wù)被提交給線程池后,分三種情況:
1泵督、當(dāng)前線程池中線程的數(shù)量小于corePoolSize趾盐,這個(gè)時(shí)候我們直接創(chuàng)建一個(gè)新線程來執(zhí)行提交的任務(wù)。
2小腊、當(dāng)線程池中的線程數(shù)大于corePoolSize時(shí)救鲤,如果線程池的狀態(tài)是RUNNING狀態(tài),并且任務(wù)加到任務(wù)隊(duì)列成功秩冈,我們?nèi)匀灰俅螜z查一下線程池的狀態(tài)本缠,防止任務(wù)在添加到任務(wù)隊(duì)列的過程中線程池被停止。如果線程池沒有被停止入问,則調(diào)用addWorker方法嘗試再創(chuàng)建一個(gè)線程去處理任務(wù)隊(duì)列丹锹。這里只是去嘗試創(chuàng)建,并不一定能創(chuàng)建成功芬失,具體addWorker的實(shí)現(xiàn)我們接下來會(huì)討論楣黍。
3、如果任務(wù)添加到任務(wù)隊(duì)列失敗棱烂,這個(gè)時(shí)候我們?cè)俅握{(diào)用addWorker方法嘗試創(chuàng)建一個(gè)新線程來處理當(dāng)前任務(wù)租漂,如果失敗,則說明線程池被shutdown或者線程池的任務(wù)隊(duì)列已經(jīng)滿了。
知道了一個(gè)任務(wù)被提交到線程池的處理流程之后哩治,我們來看一下每個(gè)步驟的具體實(shí)現(xiàn)秃踩。首先是addWorker方法,我們來看一下具體實(shí)現(xiàn):

    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;
    }

首先進(jìn)入retry循環(huán)體业筏,這個(gè)循環(huán)體的功能是去判斷線程池是否可以新創(chuàng)建線程憔杨。首先線程池的狀態(tài)如果大于SHUTDOWN狀態(tài),就不允許新創(chuàng)建線程(STOP狀態(tài):不再接受新任務(wù)也不處理任務(wù)隊(duì)列里的任務(wù)蒜胖,中斷正在進(jìn)行的任務(wù)消别;TIDYING:所有的任務(wù)被結(jié)束,workerCount被設(shè)置為0翠勉,線程狀態(tài)被轉(zhuǎn)變成TIDYING將會(huì)調(diào)用terminated()鉤子方法妖啥;TERMINATED:線程調(diào)用完terminated()方法)。如果線程池的狀態(tài)是SHUTDOWN狀態(tài)对碌,因?yàn)槲覀兺ㄟ^executor方法傳進(jìn)來的任務(wù)不是空,所以蒿偎,這個(gè)時(shí)候會(huì)返回false朽们,不回去了創(chuàng)建新的線程了。也就是說诉位,只有線程池處于RUNNING的時(shí)候才有創(chuàng)建新線程的機(jī)會(huì)骑脱。然后判斷當(dāng)前線程數(shù)是否超過了線程池的最大容量,如果是則返回false不允許創(chuàng)建苍糠。然后通過CAS操作將workerCount加一叁丧,如果成功則跳出循環(huán)創(chuàng)建線程池,如果失敗岳瞭,再次判斷線程池的狀態(tài)和進(jìn)入方法時(shí)的狀態(tài)是否一致拥娄,如果不一致則重新執(zhí)行retry循環(huán)體,如果一致瞳筏,則重新判斷線程池容量稚瘾,決定是否能夠創(chuàng)建新的線程。
如果通過以上判斷姚炕,允許創(chuàng)建新的線程摊欠,則新創(chuàng)建一個(gè)Worker對(duì)象。Worker是個(gè)什么東西呢柱宦?我們來看一下:

    private final class Worker
        extends AbstractQueuedSynchronizer
        implements Runnable
    {
        /**
         * This class will never be serialized, but we provide a
         * serialVersionUID to suppress a javac warning.
         */
        private static final long serialVersionUID = 6138294804551838833L;

        /** Thread this worker is running in.  Null if factory fails. */
        final Thread thread;
        /** Initial task to run.  Possibly null. */
        Runnable firstTask;
        /** Per-thread task counter */
        volatile long completedTasks;

        /**
         * Creates with given first task and thread from ThreadFactory.
         * @param firstTask the first task (null if none)
         */
        Worker(Runnable firstTask) {
            setState(-1); // inhibit interrupts until runWorker
            this.firstTask = firstTask;
            this.thread = getThreadFactory().newThread(this);
        }

        /** Delegates main run loop to outer runWorker  */
        public void run() {
            runWorker(this);
        }

        // Lock methods
        //
        // The value 0 represents the unlocked state.
        // The value 1 represents the locked state.

        protected boolean isHeldExclusively() {
            return getState() != 0;
        }

        protected boolean tryAcquire(int unused) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        protected boolean tryRelease(int unused) {
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        public void lock()        { acquire(1); }
        public boolean tryLock()  { return tryAcquire(1); }
        public void unlock()      { release(1); }
        public boolean isLocked() { return isHeldExclusively(); }

        void interruptIfStarted() {
            Thread t;
            if (getState() >= 0 && (t = thread) != null && !t.isInterrupted()) {
                try {
                    t.interrupt();
                } catch (SecurityException ignore) {
                }
            }
        }
    }

我們先看一下Worker的構(gòu)造方法:當(dāng)創(chuàng)建Worker對(duì)象的時(shí)候些椒,會(huì)通過我們之前設(shè)置的ThreadFactory的newThread方法來創(chuàng)建一個(gè)線程,并交給Worker對(duì)象持有掸刊。我們來看一下默認(rèn)的線程池的實(shí)現(xiàn):

public Thread newThread(Runnable r) {
            Thread t = new Thread(group, r,
                                  namePrefix + threadNumber.getAndIncrement(),
                                  0);
            if (t.isDaemon())
                t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY)
                t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }

在調(diào)用該方法的時(shí)候免糕,會(huì)把Worker對(duì)象本身傳入,我們可以看到Worker實(shí)現(xiàn)了Runnable接口。所以當(dāng)線程啟動(dòng)的時(shí)候會(huì)調(diào)用的是Worker的run()方法说墨。而Worker的run()方法調(diào)用了外部類的runWorker方法骏全,我們看一下這個(gè)方法:

    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);
        }
    }

這個(gè)方法才是線程池處理任務(wù)的整個(gè)核心內(nèi)容,進(jìn)入方法后尼斧,會(huì)進(jìn)入一個(gè)循環(huán)體:首先獲取要執(zhí)行的任務(wù)姜贡,如果當(dāng)前Worker持有的任務(wù)不是空,獲取的就是該任務(wù)棺棵,如果是空楼咳,就調(diào)用getTask()方法來獲取任務(wù)隊(duì)列里的任務(wù)。這個(gè)方法也是實(shí)現(xiàn)線程池中空閑線程銷毀的關(guān)鍵烛恤。我們來看一下它的內(nèi)部實(shí)現(xiàn):

    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;
            }
        }
    }

進(jìn)入方法的時(shí)候先定義一個(gè)標(biāo)識(shí)位timedOut母怜,這個(gè)標(biāo)識(shí)位用來表示從任務(wù)隊(duì)列中獲取任務(wù)是否超時(shí)。如果超時(shí)缚柏,說明這段時(shí)間沒有新任務(wù)過來苹熏,這個(gè)線程也就是空閑的,如果當(dāng)前線程數(shù)大于corePoolSize币喧,這個(gè)線程就會(huì)被銷毀轨域。我們來看一下這個(gè)過程是怎么實(shí)現(xiàn)的:當(dāng)設(shè)置標(biāo)識(shí)位之后,進(jìn)入一個(gè)循環(huán)體杀餐,來判斷當(dāng)前的線程池的狀態(tài)干发,如果當(dāng)前線程池的狀態(tài)大于等于STOP,方法直接返回null史翘,返回nulll是什么概念呢枉长?我們回到runWorker方法看一下,當(dāng)getTask()返回null的時(shí)候琼讽,while循環(huán)結(jié)束必峰,執(zhí)行finall語句塊里的processWorkerExit方法。執(zhí)行完這個(gè)方法后線程就會(huì)結(jié)束跨琳,也就是這個(gè)線程會(huì)被銷毀自点。我們繼續(xù)回到getTask()方法,當(dāng)前線程池的狀態(tài)大于等于STOP時(shí)脉让,不管任務(wù)隊(duì)列里是否有任務(wù)都不會(huì)獲取到任務(wù)桂敛,線程會(huì)被銷毀。當(dāng)線程池狀態(tài)是RUNNING狀態(tài)的時(shí)候會(huì)繼續(xù)接下來的判斷溅潜,當(dāng)線程池狀態(tài)是SHUTDOWN的時(shí)候要去判斷任務(wù)隊(duì)列是否為空术唬,如果是空就返回null,銷毀線程滚澜,如果不是空繼續(xù)接下來的操作粗仓。
當(dāng)進(jìn)行完上面的判斷后,在設(shè)置一個(gè)標(biāo)識(shí)位timed,這個(gè)標(biāo)識(shí)位用來表示當(dāng)獲取任務(wù)超時(shí)后是否需要銷毀線程借浊。然后進(jìn)入if ((wc > maximumPoolSize || (timed && timedOut))這個(gè)判斷塘淑,如果當(dāng)前線程數(shù)大于maximumPoolSize,說明線程被創(chuàng)建多了蚂斤,這個(gè)時(shí)候要銷毀線程存捺,直接返回null。如果獲取任務(wù)超時(shí)(第一次進(jìn)入這個(gè)循環(huán)的時(shí)候肯定不存在這種情況曙蒸,因?yàn)閠imedOut標(biāo)識(shí)位被設(shè)置成了false)捌治,并且當(dāng)前線程池里面的線程數(shù)大于1(因?yàn)橐WC線程池里必須至少有一個(gè)線程)、任務(wù)隊(duì)列是空的時(shí)候纽窟,返回null銷毀線程肖油。
結(jié)束以上判斷的時(shí)候就要去任務(wù)隊(duì)列取任務(wù),如果timed標(biāo)識(shí)位(表示當(dāng)獲取任務(wù)超時(shí)后是否需要銷毀線程)是ture臂港,就需要在給定時(shí)間內(nèi)獲取任務(wù)森枪,不然就會(huì)返回null,如果返回null审孽,就設(shè)置timedOut標(biāo)識(shí)位為ture疲恢,表示獲取任務(wù)超時(shí),當(dāng)前線程是空閑線程瓷胧。等到下次循環(huán)的時(shí)候就會(huì)結(jié)束方法返回null。如果正常獲取任務(wù)就講任務(wù)返回棚愤。到此getTask()的分析結(jié)束搓萧,我們做一個(gè)小小的總結(jié):如果線程池狀態(tài)大于STOP,直接返回null銷毀線程宛畦;如果當(dāng)前線程池狀態(tài)是SHUTDOWN并且任務(wù)隊(duì)列是空瘸洛,返回null銷毀線程;如果不是以上兩種情況次和,再判斷線程池是否設(shè)置了空閑線程銷毀反肋,如果是的話,并且從任務(wù)隊(duì)列中獲取任務(wù)超時(shí)踏施,就返回null銷毀線程石蔗;如果不是就返回獲取的線程。
當(dāng)獲取到任務(wù)之后畅形,就去判斷當(dāng)前線程池是否被stop养距,如果是,中斷當(dāng)前線程日熬,如果不是棍厌,就調(diào)用interrupted()方法取消中斷標(biāo)志。這一步是用來防止成功獲取任務(wù)之后線程池被中斷。
當(dāng)做完 以上檢查之后耘纱,調(diào)用beforeExecute(wt, task)方法敬肚,來執(zhí)行前置操作,這個(gè)方法是個(gè)模板方法束析,交由子類實(shí)現(xiàn)艳馒。之后會(huì)執(zhí)行任務(wù)的run方法,真正的執(zhí)行任務(wù)畸陡。執(zhí)行完任務(wù)之后會(huì)調(diào)用 afterExecute(task, thrown)方法來執(zhí)行后置操作鹰溜,這個(gè)方法也是模板方法。執(zhí)行完之后丁恭,會(huì)再次去獲取任務(wù)執(zhí)行以上操作曹动。getTask()方法返回null的時(shí)候,會(huì)調(diào)用processWorkerExit(w, completedAbruptly)方法牲览,這個(gè)方法做了講當(dāng)前的worker對(duì)象從線程池中去除等操作(有可能還會(huì)重新創(chuàng)建一個(gè)線程)墓陈。有興趣的同學(xué)可以看一下。
到此Worker分析結(jié)束第献,我們繼續(xù)回到addWorker方法贡必,當(dāng)我們創(chuàng)建一個(gè)Worker對(duì)象后,講worker對(duì)象添加到workers容器里庸毫。然后啟動(dòng)worker對(duì)象持有的線程仔拟。也就是用來處理任務(wù)的線程。
到此飒赃,線程池添加任務(wù)利花、處理任務(wù)的分析結(jié)束。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末载佳,一起剝皮案震驚了整個(gè)濱河市炒事,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌蔫慧,老刑警劉巖挠乳,帶你破解...
    沈念sama閱讀 207,113評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異姑躲,居然都是意外死亡睡扬,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門肋联,熙熙樓的掌柜王于貴愁眉苦臉地迎上來威蕉,“玉大人,你說我怎么就攤上這事橄仍∪驼牵” “怎么了牍戚?”我有些...
    開封第一講書人閱讀 153,340評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)虑粥。 經(jīng)常有香客問我如孝,道長(zhǎng),這世上最難降的妖魔是什么娩贷? 我笑而不...
    開封第一講書人閱讀 55,449評(píng)論 1 279
  • 正文 為了忘掉前任第晰,我火速辦了婚禮,結(jié)果婚禮上彬祖,老公的妹妹穿的比我還像新娘茁瘦。我一直安慰自己,他們只是感情好储笑,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,445評(píng)論 5 374
  • 文/花漫 我一把揭開白布甜熔。 她就那樣靜靜地躺著,像睡著了一般突倍。 火紅的嫁衣襯著肌膚如雪腔稀。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,166評(píng)論 1 284
  • 那天羽历,我揣著相機(jī)與錄音焊虏,去河邊找鬼。 笑死秕磷,一個(gè)胖子當(dāng)著我的面吹牛诵闭,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播澎嚣,決...
    沈念sama閱讀 38,442評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼涂圆,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了币叹?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,105評(píng)論 0 261
  • 序言:老撾萬榮一對(duì)情侶失蹤模狭,失蹤者是張志新(化名)和其女友劉穎颈抚,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嚼鹉,經(jīng)...
    沈念sama閱讀 43,601評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡贩汉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,066評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了锚赤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片匹舞。...
    茶點(diǎn)故事閱讀 38,161評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖线脚,靈堂內(nèi)的尸體忽然破棺而出赐稽,到底是詐尸還是另有隱情叫榕,我是刑警寧澤,帶...
    沈念sama閱讀 33,792評(píng)論 4 323
  • 正文 年R本政府宣布姊舵,位于F島的核電站晰绎,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏括丁。R本人自食惡果不足惜荞下,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,351評(píng)論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望史飞。 院中可真熱鬧尖昏,春花似錦、人聲如沸构资。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蚯窥。三九已至掸鹅,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間拦赠,已是汗流浹背巍沙。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評(píng)論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留荷鼠,地道東北人句携。 一個(gè)月前我還...
    沈念sama閱讀 45,618評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像允乐,于是被迫代替她去往敵國和親矮嫉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,916評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容