www.久久久久|狼友网站av天堂|精品国产无码a片|一级av色欲av|91在线播放视频|亚洲无码主播在线|国产精品草久在线|明星AV网站在线|污污内射久久一区|婷婷综合视频网站

當前位置:首頁 > > 充電吧
[導(dǎo)讀]? ? ? ? 作為Android中最常用跨線程手段之一,AsyncTask經(jīng)常出現(xiàn)在代碼中。我也經(jīng)常使用AsyncTask,有一次遇到一個奇怪的情況:AsyncTask.execute()函數(shù)調(diào)用后

? ? ? ? 作為Android中最常用跨線程手段之一,AsyncTask經(jīng)常出現(xiàn)在代碼中。我也經(jīng)常使用AsyncTask,有一次遇到一個奇怪的情況:AsyncTask.execute()函數(shù)調(diào)用后,AsyncTask卻未立即執(zhí)行,而是過了一段時間以后,才開始執(zhí)行,當時覺得很奇怪,一番Google后,得知是線程池的原因。事后也一直擱著,直到今天工作有點空,花了點時間看看AsyncTask的實現(xiàn)。

AsyncTask的線程池

??????? AsyncTask提供了兩個線程池,用以執(zhí)行后臺任務(wù):

??????? 當然,開發(fā)者也可以通過自定義線程池來執(zhí)行后臺任務(wù):



THREAD_POOL_EXECUTOR

??????? THREAD_POOL_EXECUTOR的定義為:

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
??????? 其中用到的一些參數(shù)如下:

    private static final int CORE_POOL_SIZE = 5;
    private static final int MAXIMUM_POOL_SIZE = 128;
    private static final int KEEP_ALIVE = 1;

    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        private final AtomicInteger mCount = new AtomicInteger(1);

        public Thread newThread(Runnable r) {
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());//創(chuàng)建一個擁有特定名字的線程
        }
    };

    private static final BlockingQueue sPoolWorkQueue =
            new LinkedBlockingQueue(10);
??????? 這里不詳細解釋ThreadPoolExecutor的實現(xiàn),而是簡單介紹下ThreadPoolExecutor的工作邏輯(線程池的工作邏輯,相信大家都比較清楚)

當線程池內(nèi)無空閑線程,且線程數(shù)不足CORE_POOL_SIZE時,創(chuàng)建新的線程來執(zhí)行任務(wù)。當線程池內(nèi)無空閑線程,且線程數(shù)大于等于CORE_POOL_SIZE,且sPoolWorkQueue為滿時,把任務(wù)放到sPoolWorkQueue中。當線程池內(nèi)無空閑線程,且線程數(shù)大于等于CORE_POOL_SZIE,且sPoolWorkQueue已滿,且線程數(shù)未達到MAXIMUM_POOL_SIZE時,創(chuàng)建新線程以執(zhí)行任務(wù)。當線程池內(nèi)無空閑線程,且線程數(shù)大于等于CORE_POOL_SZIE,且sPoolWorkQueue已滿,且線程數(shù)等于MAXIMUM_POOL_SIZE時,拋出異常。

?????? 從當前的參數(shù)我們可以看到,THREAD_POOL_EXECUTOR最多同時擁有128個線程執(zhí)行任務(wù),通常情況下(sPoolWorkQueue有任務(wù),且未滿),THREAD_POOL_EXECUTOR會擁有5條線程同時處理任務(wù)。


SERIAL_EXECUTOR

??????? 默認情況下,AsyncTask會在SERIAL_EXECUTOR中執(zhí)行后臺任務(wù)(其實,這個說法不太準確,稍后解釋):

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;        
??????? SERIAL_EXECUTOR的定義為:

    /**
     * An {@link Executor} that executes tasks one at a time in serial
     * order.  This serialization is global to a particular process.
     */
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

??????? 而SerialExecutor的定義為:
    private static class SerialExecutor implements Executor {
        final ArrayDeque mTasks = new ArrayDeque();
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                        r.run();
                    } finally {
                        scheduleNext();
                    }
                }
            });
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }
??????? 從這里,我們可以看到SerialExecutor并不是一個線程池(所以本文前面說AsyncTask的兩個線程池的說法是不準確的),它實際上是提供了一個mTask來儲存所有待執(zhí)行的task,并逐個提交給THREAD_POOL_EXECUTOR執(zhí)行。
?????? 所以,實際上所有的后臺任務(wù)都是在THREAD_POOL_EXECUTOR中執(zhí)行的,而
AsyncTask.execute()
??????? 和
AsyncTask.executorOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
??????? 的差別在于,前者會逐個執(zhí)行任務(wù),同一時間僅有一個任務(wù)被執(zhí)行。

AsyncTask的實現(xiàn)

??????? AsyncTask的實現(xiàn),需要依賴于兩個成員:

    private final WorkerRunnable mWorker;
    private final FutureTask mFuture;

WorkerRunnable

??????? WorkerRunnable的定義為:

    private static abstract class WorkerRunnable implements Callable {
        Params[] mParams;
    }
??????? 而Callable的定義為:

public interface Callable {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}
???????? WorkerRunnable為抽象類,所以使用的其實是它的子類:

   /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        mWorker = new WorkerRunnable() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                return postResult(doInBackground(mParams));
            }
        };

        mFuture = new FutureTask(mWorker) {
            @Override
            protected void done() {
                try {
                    postResultIfNotInvoked(get());
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occured while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

???????? call函數(shù)的重載挺簡單,主要就是調(diào)用doInBackground函數(shù),執(zhí)行后臺任務(wù)。


FutureTask

??????? FutureTask的實現(xiàn)比WorkerRunnable復(fù)雜,但是,如果抓住核心去分析也很簡單。

??????? 首先, FutureTask實現(xiàn)了RunnableFuture接口:

public class FutureTask implements RunnableFuture {
??????? 然后,RunnableFuture繼承自Runnable:
public interface RunnableFuture extends Runnable, Future {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}
??????? 所以,F(xiàn)utureTask類,肯定實現(xiàn)了run方法:
   public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
??????? 忽略其他處理,run函數(shù)執(zhí)行了callable的call函數(shù)。再說說callable是什么東西:
    public FutureTask(Callable callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
????? 在看看前面已經(jīng)介紹過的AsyncTask構(gòu)造函數(shù):
  /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        mWorker = new WorkerRunnable() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                return postResult(doInBackground(mParams));
            }
        };

        mFuture = new FutureTask(mWorker) {
            @Override
            protected void done() {
                try {
                    postResultIfNotInvoked(get());
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occured while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }
?????? 原來callable就是mWorker,也就是說,F(xiàn)utureTask的run函數(shù),會調(diào)用doInBackground函數(shù)。

AsyncTask.execute函數(shù)的執(zhí)行過程 ?????? 1. AsyncTask.execute
    public final AsyncTask execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }
?????? 2.AsyncTask.executeOnExecutor
    public final AsyncTask executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {
            switch (mStatus) {
                case RUNNING:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task is already running.");
                case FINISHED:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task has already been executed "
                            + "(a task can be executed only once)");
            }
        }

        mStatus = Status.RUNNING;

        onPreExecute();//調(diào)用onPreExecute

        mWorker.mParams = params;//保存參數(shù)
        exec.execute(mFuture);//執(zhí)行task

        return this;
    }
??????? 跳過SERIAL_EXECUTOR和THREAD_POOL_EXECUTOR的實現(xiàn)不談,我們可以用如下的方式,簡單理解exe.execute函數(shù):
void execute(Runnable runnable){
    new Thread(runnable).start();
}
??????? 3. FutureTask.run()
   public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
???????? 前面已經(jīng)講過,會調(diào)用mWorker.call().
???????? 4. WorkerRunnable.call()
 mWorker = new WorkerRunnable() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                return postResult(doInBackground(mParams));
            }
        };
????????? 5. AsyncTask.postResult()
    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult(this, result));
        message.sendToTarget();
        return result;
    }
???????? 通過sHandler,去UI線程執(zhí)行接下來的工作。
??????? 6. sHandler.handleMessage
    private static class InternalHandler extends Handler {
        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult result = (AsyncTaskResult) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    // There is only one result
                    result.mTask.finish(result.mData[0]);
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }
??????? 7. AsyncTask.finish
    private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }
??????? 通常情況下(即尚未調(diào)用過cancel(boolean interrupt)),isCannelled()為false,接下來會執(zhí)行onPostExecute。

總結(jié)

?????? 從本質(zhì)上來講,AsyncTask即為Execute和Handler的組合。AsyncTask利用Executor在后臺線程中執(zhí)行doInBackgroud函數(shù),并利用handler執(zhí)行onPostExecute函數(shù)。

?????? 而AsyncTask的行為則由executeOnExecutor函數(shù)中參數(shù)exec決定。AsyncTask提供的SERIAL_EXECUTOR限定任務(wù)逐個執(zhí)行,而THREAD_POOL_EXECUTOR支持最多128個任務(wù)并行執(zhí)行,但是當待處理任務(wù)過多時,會拋出RejectedExecutionException。

本站聲明: 本文章由作者或相關(guān)機構(gòu)授權(quán)發(fā)布,目的在于傳遞更多信息,并不代表本站贊同其觀點,本站亦不保證或承諾內(nèi)容真實性等。需要轉(zhuǎn)載請聯(lián)系該專欄作者,如若文章內(nèi)容侵犯您的權(quán)益,請及時聯(lián)系本站刪除。
換一批
延伸閱讀

LED驅(qū)動電源的輸入包括高壓工頻交流(即市電)、低壓直流、高壓直流、低壓高頻交流(如電子變壓器的輸出)等。

關(guān)鍵字: 驅(qū)動電源

在工業(yè)自動化蓬勃發(fā)展的當下,工業(yè)電機作為核心動力設(shè)備,其驅(qū)動電源的性能直接關(guān)系到整個系統(tǒng)的穩(wěn)定性和可靠性。其中,反電動勢抑制與過流保護是驅(qū)動電源設(shè)計中至關(guān)重要的兩個環(huán)節(jié),集成化方案的設(shè)計成為提升電機驅(qū)動性能的關(guān)鍵。

關(guān)鍵字: 工業(yè)電機 驅(qū)動電源

LED 驅(qū)動電源作為 LED 照明系統(tǒng)的 “心臟”,其穩(wěn)定性直接決定了整個照明設(shè)備的使用壽命。然而,在實際應(yīng)用中,LED 驅(qū)動電源易損壞的問題卻十分常見,不僅增加了維護成本,還影響了用戶體驗。要解決這一問題,需從設(shè)計、生...

關(guān)鍵字: 驅(qū)動電源 照明系統(tǒng) 散熱

根據(jù)LED驅(qū)動電源的公式,電感內(nèi)電流波動大小和電感值成反比,輸出紋波和輸出電容值成反比。所以加大電感值和輸出電容值可以減小紋波。

關(guān)鍵字: LED 設(shè)計 驅(qū)動電源

電動汽車(EV)作為新能源汽車的重要代表,正逐漸成為全球汽車產(chǎn)業(yè)的重要發(fā)展方向。電動汽車的核心技術(shù)之一是電機驅(qū)動控制系統(tǒng),而絕緣柵雙極型晶體管(IGBT)作為電機驅(qū)動系統(tǒng)中的關(guān)鍵元件,其性能直接影響到電動汽車的動力性能和...

關(guān)鍵字: 電動汽車 新能源 驅(qū)動電源

在現(xiàn)代城市建設(shè)中,街道及停車場照明作為基礎(chǔ)設(shè)施的重要組成部分,其質(zhì)量和效率直接關(guān)系到城市的公共安全、居民生活質(zhì)量和能源利用效率。隨著科技的進步,高亮度白光發(fā)光二極管(LED)因其獨特的優(yōu)勢逐漸取代傳統(tǒng)光源,成為大功率區(qū)域...

關(guān)鍵字: 發(fā)光二極管 驅(qū)動電源 LED

LED通用照明設(shè)計工程師會遇到許多挑戰(zhàn),如功率密度、功率因數(shù)校正(PFC)、空間受限和可靠性等。

關(guān)鍵字: LED 驅(qū)動電源 功率因數(shù)校正

在LED照明技術(shù)日益普及的今天,LED驅(qū)動電源的電磁干擾(EMI)問題成為了一個不可忽視的挑戰(zhàn)。電磁干擾不僅會影響LED燈具的正常工作,還可能對周圍電子設(shè)備造成不利影響,甚至引發(fā)系統(tǒng)故障。因此,采取有效的硬件措施來解決L...

關(guān)鍵字: LED照明技術(shù) 電磁干擾 驅(qū)動電源

開關(guān)電源具有效率高的特性,而且開關(guān)電源的變壓器體積比串聯(lián)穩(wěn)壓型電源的要小得多,電源電路比較整潔,整機重量也有所下降,所以,現(xiàn)在的LED驅(qū)動電源

關(guān)鍵字: LED 驅(qū)動電源 開關(guān)電源

LED驅(qū)動電源是把電源供應(yīng)轉(zhuǎn)換為特定的電壓電流以驅(qū)動LED發(fā)光的電壓轉(zhuǎn)換器,通常情況下:LED驅(qū)動電源的輸入包括高壓工頻交流(即市電)、低壓直流、高壓直流、低壓高頻交流(如電子變壓器的輸出)等。

關(guān)鍵字: LED 隧道燈 驅(qū)動電源
關(guān)閉