AsyncTask學習記錄

1. AsyncTask靜態變量
    1.1 線程池Thread_pool_executor及其參數
        CPU_COUNT = Runtime.getRuntime().availableProcessors();
        CORE_POOL_SIZE = CPU_COUNT + 1;
        maximum_pool_size = cpu_count * 2 + 1;
        keep_alive = 1;
        ThreadFactory sThreadFactory(AtomicInteger計數);
        BlockingQueue<Runnable> sPoolWorkQueue;
        Executor Thread_pool_executor = new ThreadPoolExecutor(core_pool_size, maximum_pool_size, keep_alive, TimeUtils.Seconds, sPoolWorkQueue, sThreadFactory);
    1.2 順序執行線程的SERIAL_EXECUTOR(默認執行器volatile sDefaultExecutor)
        class SerialExecutor implements Executor {
            ArrayDeque<Runnable> mTasks;
            Runnable mActive;
            synchronized void execute(Runnnable r);
            synchronized void scheduleNext();
        }
    1.3 Message和Handler
        message_post_result
        message_post_progress
        sHandler
2. AsyncTask普通變量
    1. Callable
        WorkRunnable<Params, Result> mWorker;
        FutureTask<Result> mFuture(mWorker);
    2. 狀態
        volatile mStates;
        AtomicBoolean mCancelled;
        AtomicBoolean mTaskInvoked;
3. 流程
    mAsyncTask.execute(Params...)
    ->executeOnExecutor(sDefaultExecutor, params)
        1. 判斷狀態mStates是否爲pending
        2. 設置狀態mStates爲Running
        3. onPreExecute()     // 重載實現
        4. mWorker.mParams = params;
            exec.execute(mFuture);
            4.1 SerialExecutor
            synchronized void execute(mFuture) {
                mTasks.offer(new Runnable{mFuture.run(); scheduleNext();}); // new 一個Runnable添加在數組隊列mTask中,Runnable中運行mFuture和scheduleNext;
                (mActive == null) = true, scheduleNext();    // mActive當前正在執行Runnable=null,執行next.
            }
            synchronized void scheduleNext() {
                if ((mActive=mTask.poll()) !=null)   //剛在execute中offer,所以不爲null
                    Thread_pool_executor.execute(mActive);   //在線程池中執行mActive(mActive中執行mFuture, 最終執行了mFuture)
            }
            4.2 mFuture(在線程池中執行)
            mFuture中的Callable參數爲mWorker,所以執行mWorker.call()
            mWorker::Result call() {
                mTaskInvoked.set(true);        // 設置狀態爲已調用
                Process.setThreadPriority(Process.thread_priority_background);   // 設置任務爲後臺任務

                result = doInBackground(mParams);    // 重載實現
                Binder.flushPendingCommand();    
                return postResult(result);    // 發送post_result消息給handler,返回result本身
                    4.2.1
                    Result postResult(Result result) {
                        Message msg = sHandler.obtionMsg(Message_post_result, new AsyncTaskResult(this, result));
                        msg.sendToTarget();
                        return result;
                    }
                    4.2.2
                    sHandler收到post_result消息,
                        msg.obj.mTask.finish(msg.obj.mData[0]);  // msg.obj爲this,即本AsyncTask的finish方法
                    void finish(Result result) {
                        if (isCancelled()) {onCancelled(result);}   // 重載實現
                        else {onPostExecute(result);}    // 重載實現
                        mStates = FINISH;    // 置狀態爲結束
                    }
            }
            mFuture::void done() {
                postResultIfNotInvoked(get());   // get()拿到mWorker的call的result
                    void postResultIfNotInvoked(Result result) {
                        if (!mTaskInvoked.get())    //  在call中置爲true
                            postResult(result);
                    }
            }
        5. return this;
4. Others
    4.1 阻塞問題
    api11後AsyncTask默認是串行執行任務,即順序執行。所以在AsyncTask中只能進行短時的操作,防止阻塞線程池。
    調用executeOnExecutor(AsyncTask.Thread_pool_executor)來立即執行任務,但限於線程池的最大併發數,也有可能導致阻塞。
    4.2 cancel問題
    cancel方法調用的是Thread.interrupt(),只是將中止狀態置爲true,並不能真正的cancel任務的doInBackground方法。
    只能是自己在doInBackground中進行中斷處理。
    4.3 多任務管理問題
    AsyncTask只能執行一次execute,所以有多個後臺任務時,只能設置多個AsyncTask,在退出的時候需要對多個AsyncTask做處理

    來避免UI問題及內存泄漏,問題(如Thread異常等)排查困難。


參考:

http://www.jianshu.com/p/d83fd0e8a062

http://www.jianshu.com/p/de424983ba83

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章