Asynctask原理分析

Asynctask是一種輕量級異步任務(wù)類,任務(wù)是在線程池中執(zhí)行后臺任務(wù)的,并將結(jié)果返回到UI界面。它封裝了handler和thread,但是asynctask不適合特別耗時的任務(wù),耗時任務(wù)建議使用線程池。

1.方法介紹

核心方法四個:onPreExecute()、doInBackground()、onProgressUpdate()、onPostExecute(),這四個方法除了doInBackground()其余都存在了主線程

2.注意點

1)Asynctask類初始加載應(yīng)該在主線程,android5.0以后activitythread的main方法中,已經(jīng)將這個類初始化了
2)Asynctask創(chuàng)建對象,也應(yīng)該在主線程
3)execute方法要在主線程
4)不能手動調(diào)用asynctask的四個核心方法
5)一個Asynctask對象,只能調(diào)用一次execute方法
6)android1.6以前是串行,3.0以后既可以串行也可以并行

3.源碼分析

Asynctask原理圖

首先來解釋一下,剛創(chuàng)建完成asynctask對象后,會執(zhí)行execute()方法,然后執(zhí)行onpreExecute(),接下來asynctask里面的線程池就開始工作了。在Asynctask創(chuàng)建的同時,會將doInBackground()這個方法體封裝進一個callable當中,然后再進行封轉(zhuǎn)到并發(fā)類Futuretask中,代碼如下:

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

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

        mFuture = new FutureTask<Result>(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);
                }
            }
        };
    }

線程池在執(zhí)行execute方法的時候,會先將任務(wù)添加到隊列中,如果當前沒有活動的任務(wù),就會執(zhí)行scheduleNext()來執(zhí)行下一個任務(wù)。從這一個角度來看,asynctask是串行的。代碼如下:

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

在執(zhí)行Futuretask的run方法的時候,最后會調(diào)用到WorkerRunnable的call方法,進而執(zhí)行doinbackground方法,會把返回值傳給postResult方法,它會通過sHandler發(fā)送一個消息,handler處理消息會讓Asynctask執(zhí)行finish方法

 private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }
這里又涉及到handler切換線程的工作,我這里再來講解一下,postresult是在WorkerRunnable中調(diào)用的,而WorkerRunnable又被封裝進了FutureTask,要知道這個類是一個runnable也就是說它是一個線程,而Asynctask是創(chuàng)建在主線程中的,這不就是兩個線程的切換嗎???在runnable中調(diào)用了handler,而handler創(chuàng)建在了主線程中,這就直接切換到了主線程。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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