日本黄色一级经典视频|伊人久久精品视频|亚洲黄色色周成人视频九九九|av免费网址黄色小短片|黄色Av无码亚洲成年人|亚洲1区2区3区无码|真人黄片免费观看|无码一级小说欧美日免费三级|日韩中文字幕91在线看|精品久久久无码中文字幕边打电话

當(dāng)前位置:首頁 > 芯聞號 > 充電吧
[導(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í)行,當(dāng)時覺得很奇怪,一番Google后,得知是線程池的原因。事后也一直擱著,直到今天工作有點(diǎn)空,花了點(diǎn)時間看看AsyncTask的實(shí)現(xiàn)。

AsyncTask的線程池

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

??????? 當(dāng)然,開發(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);
??????? 這里不詳細(xì)解釋ThreadPoolExecutor的實(shí)現(xiàn),而是簡單介紹下ThreadPoolExecutor的工作邏輯(線程池的工作邏輯,相信大家都比較清楚)

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

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


SERIAL_EXECUTOR

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

    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的兩個線程池的說法是不準(zhǔn)確的),它實(shí)際上是提供了一個mTask來儲存所有待執(zhí)行的task,并逐個提交給THREAD_POOL_EXECUTOR執(zhí)行。
?????? 所以,實(shí)際上所有的后臺任務(wù)都是在THREAD_POOL_EXECUTOR中執(zhí)行的,而
AsyncTask.execute()
??????? 和
AsyncTask.executorOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
??????? 的差別在于,前者會逐個執(zhí)行任務(wù),同一時間僅有一個任務(wù)被執(zhí)行。

AsyncTask的實(shí)現(xiàn)

??????? AsyncTask的實(shí)現(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為抽象類,所以使用的其實(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);
                }
            }
        };
    }

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


FutureTask

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

??????? 首先, FutureTask實(shí)現(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類,肯定實(shí)現(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的實(shí)現(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í)行,但是當(dāng)待處理任務(wù)過多時,會拋出RejectedExecutionException。

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