AsyncTask原理分析

AsyncTask在安卓中常用于線程間通信。在子線程執(zhí)行耗時(shí)任務(wù),在主線程更新UI。

AsyncTask內(nèi)部封裝了Handler和線程池。

1、AsyncTask主要靠InternalHandler去跟主線程通信,InternalHandler繼承自Handler類,在handleMessage方法里面處理了消息。

private static class InternalHandler extends Handler {
        public InternalHandler() {
            super(Looper.getMainLooper());
        }

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

2、有兩個(gè)線程池THREAD_POOL_EXECUTOR和SERIAL_EXECUTOR
SERIAL_EXECUTOR負(fù)責(zé)隊(duì)列管理,負(fù)責(zé)執(zhí)行任務(wù)的是THREAD_POOL_EXECUTOR

private static class SerialExecutor implements Executor {
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        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);
            }
        }
    }

回過頭來,咱們?cè)賮砜纯磂xecuteOnExecutor方法

@MainThread
    public final AsyncTask<Params, Progress, Result> 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();

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }

這個(gè)方法里面做了下狀態(tài)判斷和狀態(tài)修改,所以可以看出,一個(gè)AsyncTask實(shí)例只能執(zhí)行一次。然后分別調(diào)用了onPreExecute和exec.execute(mFuture),這里的exec就是SERIAL_EXECUTOR,調(diào)用exec.execute(mFuture)就是把任務(wù)插入到任務(wù)隊(duì)列中。然后依次執(zhí)行任務(wù)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容