溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android線程池是什么

發(fā)布時間:2021-12-23 16:29:39 來源:億速云 閱讀:141 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“Android線程池是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“Android線程池是什么”吧!

我們都知道線程池的用法,一般就是先new一個ThreadPoolExecutor對象,再調(diào)用execute(Runnable runnable)傳入我們的Runnable,剩下的交給線程池處理就行了,于是這次我就從ThreadPoolExecutor的execute方法看起:

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();
        //1.如果workerCountOf(c)即正在運行的線程數(shù)小于核心線程數(shù),就執(zhí)行addWork
        if (workerCountOf(c) < corePoolSize) {
            if (addWorker(command, true)) 
                return;
            c = ctl.get();
        }
        //2.如果線程池還在運行狀態(tài)并且把任務(wù)添加到任務(wù)隊列成功
        if (isRunning(c) && workQueue.offer(command)) {
            int recheck = ctl.get();
            //3.如果線程池不在運行狀態(tài)并且從任務(wù)隊列移除任務(wù)成功,執(zhí)行線程池飽和策略(默認(rèn)直接拋出異常)
            if (! isRunning(recheck) && remove(command))
                reject(command);
            //4.否則如果此時運行線程數(shù)==0,就直接調(diào)用addWork方法
            else if (workerCountOf(recheck) == 0)
                addWorker(null, false);
        }
        //5.如果2條件不成立,繼續(xù)判斷如果addWork返回false,執(zhí)行線程池飽和策略
        else if (!addWorker(command, false))
            reject(command);
    }

大致過程就是如果核心線程未滿,則直接addWorker(該方法下面會再分析);如果核心線程已滿,則嘗試將任務(wù)加進(jìn)消息隊列中,并再判斷如果此時運行線程數(shù)==0則調(diào)addWorker方法,否則不做任何處理(因為運行的線程處理完自己的任務(wù)后會去消息隊列中取任務(wù)來執(zhí)行,下面會分析);如果任務(wù)隊列添加任務(wù)失敗,那么直接addWorker(),如果addWorker返回false,執(zhí)行飽和策略,下面我們就來看看addWorker里面做了什么

/**
     * @param firstTask the task the new thread should run first (or
     * null if none). Workers are created with an initial first task
     * (in method execute()) to bypass queuing when there are fewer
     * than corePoolSize threads (in which case we always start one),
     * or when the queue is full (in which case we must bypass queue).
     * Initially idle threads are usually created via
     * prestartCoreThread or to replace other dying workers.
     *
     * @param core if true use corePoolSize as bound, else
     * maximumPoolSize. (A boolean indicator is used here rather than a
     * value to ensure reads of fresh values after checking other pool
     * state).
     * @return true if successful
     */
    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);
                //1.如果正在運行的線程數(shù)大于corePoolSize 或 maximumPoolSize(core代表以核心線程數(shù)還是最大線程數(shù)為邊界),return false,表示addWorker失敗
                if (wc >= CAPACITY ||
                    wc >= (core ? corePoolSize : maximumPoolSize))
                    return false;
                //2.否則將運行線程數(shù)+1,并跳出這個for循環(huán)
                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 {
            //3.創(chuàng)建一個Worker對象,傳入我們的runnable
            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) {
                    //4.開始啟動線程
                    t.start();
                    workerStarted = true;
                }
            }
        } finally {
            if (! workerStarted)
                addWorkerFailed(w);
        }
        return workerStarted;
    }
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);
        }
final void runWorker(Worker w) {
        Thread wt = Thread.currentThread();
        Runnable task = w.firstTask;
        w.firstTask = null;
        w.unlock(); // allow interrupts
        boolean completedAbruptly = true;
        try {
            //1.當(dāng)firstTask不為空或getTask不為空時一直循環(huán)
            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 {
                        //2.執(zhí)行任務(wù)
                        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);
        }
    }

可以看到addWorker方法主要就是先判斷正在運行線程數(shù)是否超過了最大線程數(shù)(具體根據(jù)邊界取),如果未超過則創(chuàng)建一個worker對象,其中firstTask是我們傳入的Runnable,當(dāng)然根據(jù)上面的execute方法可知當(dāng)4條件滿足時,傳入的firstTask是null,Thread是用ThreadFactory創(chuàng)建的線程,傳入的Runnable是Worker自己,最后開啟線程,于是執(zhí)行Worker這里的run、runWorker方法,在runWorker方法里,開啟一個while循環(huán),當(dāng)firstTask不為空或getTask不為空時,執(zhí)行task,下面我們接著看看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?
            //1.會不會淘汰空閑線程
            boolean timed = allowCoreThreadTimeOut || wc > corePoolSize;
            //2.return null意味著回收一個Worker即淘汰一個線程
            if ((wc > maximumPoolSize || (timed && timedOut))
                && (wc > 1 || workQueue.isEmpty())) {
                if (compareAndDecrementWorkerCount(c))
                    return null;
                continue;
            }
 
            try {
                //3.等待指定時間
                Runnable r = timed ?
                    workQueue.poll(keepAliveTime, TimeUnit.NANOSECONDS) :
                    workQueue.take();
                if (r != null)
                    return r;
                timedOut = true;
            } catch (InterruptedException retry) {
                timedOut = false;
            }
        }
    }

可以看1、2注釋,allowCoreThreadTimeOut代表存活一定時間是否對核心線程有效(默認(rèn)為false),先看它為ture的情況,此時不管是核心線程還是非核心線程在3處都會等待一定時間(就是我們傳入的線程?;顣r間),等待時間內(nèi)如果從任務(wù)隊列取到任務(wù),則返回執(zhí)行,否則timeout為true,繼續(xù)走到2,由于(timed && timedOut)和workQueue.isEmpty()均為true,返回null,代表回收一個線程;如果allowCoreThreadTimeOut為false,代表不回收核心線程,此時如果在3處沒有取到任務(wù),繼續(xù)執(zhí)行到2處,只有當(dāng)wc > corePoolSize或wc > maximumPoolSize時才會執(zhí)行return null,否則一直循環(huán),相當(dāng)于該線程一直處于運行狀態(tài),直到從任務(wù)隊列拿到新的任務(wù)

到此,相信大家對“Android線程池是什么”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI