Android Handler机制13之AsyncTask源码解析

Android Handler机制系列文章整体内容如下:

本篇文章的主要内容如下:

  • 1、AsyncTask概述
  • 2、基本用法
  • 3、AsyncTask类源码解析
  • 4、AsyncTask类的构造函数
  • 5、AsyncTask类核心方法解析
  • 6、AsyncTask核心流程
  • 7、AsyncTask与Handler

AsyncTask官网
AsyncTask源码

一、AsyncTask概述

我们都知道,Android UI线程是不安全的,如果想要在子线程里面进行UI操作,就需要直接Android的异步消息处理机制,前面我写了很多文章从源码层面分析了Android异步消息Handler的处理机制。感兴趣的可以去了解下。不过为了更方便我们在子线程中更新UI元素,Android1.5版本就引入了一个AsyncTask类,使用它就可以非常灵活方便地从子线程切换到UI线程。

二、基本用法

AsyncTask是一个抽象类,我们需要创建子类去继承它,并且重写一些方法。AsyncTask接受三个泛型的参数:

  • Params:指定传给任务执行时的参数的类型
  • Progress:指定后台任务执行时将任务进度返回给UI线程的参数类型
  • Result:指定任务完成后返回的结果类型

除了指定泛型参数,还需要根据重写一些方法,常用的如下:

  • onPreExecute():这个方法在UI线程调用,用于在任务执行器那做一些初始化操作,如在界面上显示加载进度空间
  • onInBackground:在onPreExecute()结束之后立刻在后台线程调用,用于耗时操作。在这个方法中可调用publishProgress方法返回任务的执行进度。
  • onProgressUpdate:在doInBackground调用publishProgress后被调用,工作在UI线程
  • onPostExecute:后台任务结束后被调用,工作在UI线程。

三、AsyncTask类源码解析

AsyncTask.java源码地址

(一)、类注释翻译

源码注释如下:

/**
 * <p>AsyncTask enables proper and easy use of the UI thread. This class allows you
 * to perform background operations and publish results on the UI thread without
 * having to manipulate threads and/or handlers.</p>
 *
 * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler}
 * and does not constitute a generic threading framework. AsyncTasks should ideally be
 * used for short operations (a few seconds at the most.) If you need to keep threads
 * running for long periods of time, it is highly recommended you use the various APIs
 * provided by the <code>java.util.concurrent</code> package such as {@link Executor},
 * {@link ThreadPoolExecutor} and {@link FutureTask}.</p>
 *
 * <p>An asynchronous task is defined by a computation that runs on a background thread and
 * whose result is published on the UI thread. An asynchronous task is defined by 3 generic
 * types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
 * and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>,
 * <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p>
 *
 * <div class="special reference">
 * <h3>Developer Guides</h3>
 * <p>For more information about using tasks and threads, read the
 * <a href="{@docRoot}guide/components/processes-and-threads.html">Processes and
 * Threads</a> developer guide.</p>
 * </div>
 *
 * <h2>Usage</h2>
 * <p>AsyncTask must be subclassed to be used. The subclass will override at least
 * one method ({@link #doInBackground}), and most often will override a
 * second one ({@link #onPostExecute}.)</p>
 *
 * <p>Here is an example of subclassing:</p>
 * <pre class="prettyprint">
 * private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 *     protected Long doInBackground(URL... urls) {
 *         int count = urls.length;
 *         long totalSize = 0;
 *         for (int i = 0; i < count; i++) {
 *             totalSize += Downloader.downloadFile(urls[i]);
 *             publishProgress((int) ((i / (float) count) * 100));
 *             // Escape early if cancel() is called
 *             if (isCancelled()) break;
 *         }
 *         return totalSize;
 *     }
 *
 *     protected void onProgressUpdate(Integer... progress) {
 *         setProgressPercent(progress[0]);
 *     }
 *
 *     protected void onPostExecute(Long result) {
 *         showDialog("Downloaded " + result + " bytes");
 *     }
 * }
 * </pre>
 *
 * <p>Once created, a task is executed very simply:</p>
 * <pre class="prettyprint">
 * new DownloadFilesTask().execute(url1, url2, url3);
 * </pre>
 *
 * <h2>AsyncTask's generic types</h2>
 * <p>The three types used by an asynchronous task are the following:</p>
 * <ol>
 *     <li><code>Params</code>, the type of the parameters sent to the task upon
 *     execution.</li>
 *     <li><code>Progress</code>, the type of the progress units published during
 *     the background computation.</li>
 *     <li><code>Result</code>, the type of the result of the background
 *     computation.</li>
 * </ol>
 * <p>Not all types are always used by an asynchronous task. To mark a type as unused,
 * simply use the type {@link Void}:</p>
 * <pre>
 * private class MyTask extends AsyncTask<Void, Void, Void> { ... }
 * </pre>
 *
 * <h2>The 4 steps</h2>
 * <p>When an asynchronous task is executed, the task goes through 4 steps:</p>
 * <ol>
 *     <li>{@link #onPreExecute()}, invoked on the UI thread before the task
 *     is executed. This step is normally used to setup the task, for instance by
 *     showing a progress bar in the user interface.</li>
 *     <li>{@link #doInBackground}, invoked on the background thread
 *     immediately after {@link #onPreExecute()} finishes executing. This step is used
 *     to perform background computation that can take a long time. The parameters
 *     of the asynchronous task are passed to this step. The result of the computation must
 *     be returned by this step and will be passed back to the last step. This step
 *     can also use {@link #publishProgress} to publish one or more units
 *     of progress. These values are published on the UI thread, in the
 *     {@link #onProgressUpdate} step.</li>
 *     <li>{@link #onProgressUpdate}, invoked on the UI thread after a
 *     call to {@link #publishProgress}. The timing of the execution is
 *     undefined. This method is used to display any form of progress in the user
 *     interface while the background computation is still executing. For instance,
 *     it can be used to animate a progress bar or show logs in a text field.</li>
 *     <li>{@link #onPostExecute}, invoked on the UI thread after the background
 *     computation finishes. The result of the background computation is passed to
 *     this step as a parameter.</li>
 * </ol>
 * 
 * <h2>Cancelling a task</h2>
 * <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking
 * this method will cause subsequent calls to {@link #isCancelled()} to return true.
 * After invoking this method, {@link #onCancelled(Object)}, instead of
 * {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])}
 * returns. To ensure that a task is cancelled as quickly as possible, you should always
 * check the return value of {@link #isCancelled()} periodically from
 * {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p>
 *
 * <h2>Threading rules</h2>
 * <p>There are a few threading rules that must be followed for this class to
 * work properly:</p>
 * <ul>
 *     <li>The AsyncTask class must be loaded on the UI thread. This is done
 *     automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li>
 *     <li>The task instance must be created on the UI thread.</li>
 *     <li>{@link #execute} must be invoked on the UI thread.</li>
 *     <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute},
 *     {@link #doInBackground}, {@link #onProgressUpdate} manually.</li>
 *     <li>The task can be executed only once (an exception will be thrown if
 *     a second execution is attempted.)</li>
 * </ul>
 *
 * <h2>Memory observability</h2>
 * <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following
 * operations are safe without explicit synchronizations.</p>
 * <ul>
 *     <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them
 *     in {@link #doInBackground}.
 *     <li>Set member fields in {@link #doInBackground}, and refer to them in
 *     {@link #onProgressUpdate} and {@link #onPostExecute}.
 * </ul>
 *
 * <h2>Order of execution</h2>
 * <p>When first introduced, AsyncTasks were executed serially on a single background
 * thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
 * to a pool of threads allowing multiple tasks to operate in parallel. Starting with
 * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single
 * thread to avoid common application errors caused by parallel execution.</p>
 * <p>If you truly want parallel execution, you can invoke
 * {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with
 * {@link #THREAD_POOL_EXECUTOR}.</p>
 */

简单翻译一下:

  • AsyncTask可以轻松的正确使用UI线程,该类允许你执行后台操作并在UI线程更新结果,从而避免了无需使用Handler来操作线程
  • AsyncTask是围绕Thread与Handler而设计的辅助类,所以它并不是一个通用的线程框架。理想情况下,AsyncTask应该用于短操作(最多几秒)。如果你的需求是在长时间保持线程运行,强烈建议您使用由
    java.util.concurrent提供的各种API包,比如Executor、ThreadPoolExecutor或者FutureTask。
  • 一个异步任务被定义为:在后台线程上运行,并在UI线程更新结果。一个异步任务通常由三个类型:Params、Progress和Result。以及4个步骤:onPreExecute、doInBackground、onProgressUpdate、onPostExecute。
  • 用法:AsyncTask必须由子类实现后才能使用,它的子类至少重写doInBackground()这个方法,并且通常也会重写onPostExecute()这个方法
  • 下面是一个继承AsyncTask类的一个子类的例子
   private class DownloadFilesTask extends AsyncTask<URL, >Integer, Long>
   {
       protected Long doInBackground(URL... urls) {
           int count = urls.length;
           long totalSize = 0;
           for (int i = 0; i < count; i++) {
               totalSize += Downloader.downloadFile(urls[i]);
               publishProgress((int) ((i / (float) count) * 100));
               // Escape early if cancel() is called
               if (isCancelled()) break;
           }
           return totalSize;
       }

       protected void onProgressUpdate(Integer... progress) {
           setProgressPercent(progress[0]);
       }

       protected void onPostExecute(Long result) {
           showDialog("Downloaded " + result + " bytes");
       }
   }

一旦创建,任务会被很轻松的执行。就像下面这块代码一样

new DownloadFilesTask().execute(url1,url2,url3);
  • AsyncTask泛型,在异步任务中通常有三个泛型
    • Params:发送给任务的参数类型,这个类型会被任务执行
    • Progress:后台线程进度的计算的基本单位。
    • Result:后台线程执行的结果类型。
  • 如果异步任务不需要上面类型,则可以需要声明类型未使用,通过使用Void来表示类型未使用。就像下面一杨
private class MyTask extends AsyncTask<Void, Void, Void>{...}
  • 四个步骤
    • onPreExecute() 在执行任务之前在UI线程上调用,此步骤通常用于初始化任务,例如在用户界面显示进度条。
    • doInBackground() 方法在 onPreExecute()执行完成后调用的。doInBackground()这个方法用于执行可能需要很长时间的首台计算。异步任务的参数被传递到这个步骤中。计算结果必须经由这个步骤返回。这个步骤内还可以调用publishProgress()方法发布一个或者多个进度单位。在调用onProgressUpdate()函数后,这个结果将在UI线程上更新。
    • onProgressUpdate()方法:在调用publishProgress()之后在UI线程上调用。具体的执行时间不确定,该方法用于在后台计算的异步任务,把具体的进度显示在用户界面。例如,它可以用于对进度条进行动画处理或者在文本字段中显示日志。
    • onPostExecute()方法, 后台任务完成后,在UI线程调用onPostExecute()方法,后台运行的结果作为参数传递给这个方法
  • 取消任务
    在任何时候都可以通过调用cancel(boolean)来取消任务。调用此方法将导致isCancelled()方法的后续调用返回true。调用此方法后,在执行doInBackground(Object [])方法后,将调用onCancelled(object),而不是onPostExecute(Object)方法。为了尽可能快的取消任务,如果可能的话,你应该在调用doInBackground(Object[])之前检查isCancelled()的返回值。
  • 线程规则,这个类必须遵循有关线程的一些规则才能正常使用,规则如下:
    • 必须在UI线程上加载AsyncTask类,android4.1上自动完成
    • 任务实例必须在UI线程上实例化
    • execute()方法必须在主线程上调用
    • 不要手动去调用onPreExecute()、onPostExecute()、doInBackground()、onProgressUpdate()方法。
    • 这个任务只能执行一次(如果尝试第二次执行,将会抛出异常)。
      该任务只能执行一次(如果尝试第二次执行,将抛出异常)。
  • 内存的观察AsyncTask。保证所有回调调用都是同步的,使得以下操作在没有显示同步情况下是安全的。
    • 在构造函数或者onPreExecute设置成员变量,并且在doInBackground()方法中引用它们。
    • 在doInBackground()设置成员字段,并在onProgressUpdate()和onPostExecute()方法中引用他们。
  • 执行顺序。第一引入AsyncTask时,AsyncTasks是在单个后台线程串行执行的。在android1.6以后,这被更改为允许多个任务并行操作的线程池。从android 3.0开始,每个任务都是执行在一个独立的线程上,这样可以避免一些并行执行引起的常见的应用程序错误。如果你想要并行执行,可以使用THREAD_POOL_EXECUTOR来调用executeOnExecutor()方法。

至此这个类的注释翻译完毕,好长啊,大家看完翻译,是不是发现了很多之前没有考虑到的问题。

(二)、AsyncTask的结构

AsyncTask的结构如下:

AsyncTask的结构.png

我们看到在AsyncTask有4个自定义类,一个枚举类,一个静态块,然后才是这个类的具体变量和属性,那我们就依次讲解

(三)、枚举Status

代码在AsyncTask.java 256行

    /**
     * Indicates the current status of the task. Each status will be set only once
     * during the lifetime of a task.
     */
   
    public enum Status {
        /**
         * Indicates that the task has not been executed yet.
         */
        PENDING,
        /**
         * Indicates that the task is running.
         */
        RUNNING,
        /**
         * Indicates that {@link AsyncTask#onPostExecute} has finished.
         */
        FINISHED,
    }

枚举Status上的注释翻译一下就是:

Status表示当前任务的状态,每种状态只能在任务的生命周期内设置一次。

所以任务有三种状态

  • PENDING:表示任务尚未执行的状态
  • RUNNING:表示任务正在执行
  • FINISHED:任务已完成

(四)、私有的静态类InternalHandler

代码在AsyncTask.java 656行

    private static class InternalHandler extends Handler {
        public InternalHandler() {
            // 这个handler是关联到主线程的
            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;
            }
        }
    }

通过上面的代码我们知道:

  • InternalHandler继承自Handler,并且在它的构造函数里面调用了Looper.getMainLooper(),所以我们知道这个Handler是关联主线程的。
  • 重写了handleMessage(Message)方法,其中这个Message的obj这个类型是AsyncTaskResult(AsyncTaskResult我将在下面讲解),然后根据msg.what的来区别。
  • 我们知道这个Message只有两个标示,一个是MESSAGE_POST_RESULT代表消息的结果,一个是MESSAGE_POST_PROGRESS代表要执行onProgressUpdate()方法。

通过这段代码我们可以推测AsyncTask内部实现线程切换,即切换到主线程是通过Handler来实现的。

(五)、私有的静态类AsyncTaskResult

代码在AsyncTask.java 682行

    @SuppressWarnings({"RawUseOfParameterizedType"})
    private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }

通过类名,我们大概可以推测出这一个负责AsyncTask结果的类

AsyncTaskResult这个类 有两个成员变量,一个是AsyncTask一个是泛型的数组。

  • mTask参数:是为了AsyncTask是方便在handler的handlerMessage回调中方便调用AsyncTask的本身回调函数,比如onPostExecute()函数、onPreogressUpdata()函数,所以在AsyncTaskResult需要持有AsyncTask。
  • mData参数:既然是代表结果,那么肯定要有一个变量持有这个计算结果

(六)、私有静态抽象类WorkerRunnable

代码在AsyncTask.java 677行

    private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

这个抽象类很简答,首先是实现了Callable接口,然后里面有个变量
mParams,类型是泛型传进来的数组

(七)、局部变量详解

AsyncTask的局部变量如下:

    private static final String LOG_TAG = "AsyncTask";

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    // We want at least 2 threads and at most 4 threads in the core pool,
    // preferring to have 1 less than the CPU count to avoid saturating
    // the CPU with background work
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE_SECONDS = 30;

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

    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    public static final Executor THREAD_POOL_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();

    private static final int MESSAGE_POST_RESULT = 0x1;
    private static final int MESSAGE_POST_PROGRESS = 0x2;

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    private static InternalHandler sHandler;

    private final WorkerRunnable<Params, Result> mWorker;
    private final FutureTask<Result> mFuture;

    private volatile Status mStatus = Status.PENDING;
    
    private final AtomicBoolean mCancelled = new AtomicBoolean();
    private final AtomicBoolean mTaskInvoked = new AtomicBoolean();

那我们就来一一解答

  • String LOG_TAG = "AsyncTask":打印专用
  • CPU_COUNT = Runtime.getRuntime().availableProcessors():获取当前CPU的核心数
  • CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4)):线程池的核心容量,通过代码我们知道是一个大于等于2小于等于4的数
  • MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1:线程池的最大容量是2倍的CPU核心数+1
  • KEEP_ALIVE_SECONDS = 30:过剩的空闲线程的存活时间,一般是30秒
  • sThreadFactory:线程工厂,通过new Thread来获取新线程,里面通过使用AtomicInteger原子整数保证超高并发下可以正常工作。
  • sPoolWorkQueue:静态阻塞式队列,用来存放待执行的任务,初始容量:128个
  • THREAD_POOL_EXECUTOR:线程池
  • SERIAL_EXECUTOR = new SerialExecutor():静态串行任务执行器,其内部实现了串行控制,循环的取出一个个任务交给上述的并发线程池去执行。
  • MESSAGE_POST_RESULT = 0x1:消息类型,代表发送结果
  • MESSAGE_POST_PROGRESS = 0x2:消息类型,代表进度
  • sDefaultExecutor = SERIAL_EXECUTOR:默认任务执行器,被赋值为串行任务执行器,就是因为它,AsyncTask变成了串行的了。
  • sHandler:静态Handler,用来发送上面的两种通知,采用UI线程的Looper来处理消息,这就是为什么AnsyncTask可以在UI线程更新UI
  • WorkerRunnable<Params, Result> mWorke:是一个实现Callback的抽象类,扩展了Callable多了一个Params参数。
  • mFuture:FutureTask对象
  • mStatus = Status.PENDING:任务的状态默认为挂起,即等待执行,其类型标示为volatile
  • mCancelled = new AtomicBoolean():原子布尔类型,支持高并发访问,标示任务是否被取消
  • mTaskInvoked = new AtomicBoolean():原子布尔类型,支持高并发访问,标示任务是否被执行过

(八)、静态代码块

代码在AsyncTask.java 226行

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                sPoolWorkQueue, sThreadFactory);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

通过上面的(七)、局部变量详解,我们知道在静态代码块中创建了一个线程池threadPoolExecutor,并设置了核心线程会超时关闭,最后并把这个线程池指向THREAD_POOL_EXECUTOR。

(九)、私有的静态类SerialExecutor

代码在AsyncTask.java 226行

    private static class SerialExecutor implements Executor {
        // 循环数组实现的双向Queue,大小是2的倍数,默认是16,有队头和队尾巴两个下标
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        // 正在运行runnable
        Runnable mActive;

        public synchronized void execute(final Runnable r) {
            // 添加到双向队列中去
            mTasks.offer(new Runnable() {
                public void run() {
                    try {
                         //执行run方法
                        r.run();
                    } finally {
                        //无论执行结果如何都会取出下一个任务执行
                        scheduleNext();
                    }
                }
            });
           // 如果没有活动的runnable,则从双端队列里面取出一个runnable放到线程池中运行
           // 第一个请求任务过来的时候mActive是空的
            if (mActive == null) {
                 //取出下一个任务来
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
            //从双端队列中取出一个任务
            if ((mActive = mTasks.poll()) != null) {
                //线线程池执行取出来的任务,真正的执行任务
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }
  • 首先,注意SerialExecutor的execute是synchronized的,所以无论多个少任务调用execute()都是同步的。
  • 其次,SerialExecutor里面一个ArrayDeque队列,通过代码我们知道,SerialExecutor是通过ArrayDeque来管理Runnable对象的。通过上面我们知道execute()是同步的,所以如果你有10个任务同时调用SerialExecutor的execute()方法,就会把10个Runnable先后放入到mTasks中去,可见mTasks缓存了将要执行的Runnable。
  • 再次1,如果我们第一个执行execute()方法时,会调用ArrayDeque的offer()方法将传入的Runnable对象添加到队列的尾部,然后判断mActive是不是null,因为是第一次调用,此时mActive还没有赋值,所以mActive等于null。所以此时mActive == null成立,所以会调用scheduleNext()方法。
  • 再次2,我们在调用scheduleNext()里面,看到会调用mTasks.poll(),我们知道这是从队列中取出头部元素,然后把这个头部元素赋值给mActive,然后让THREAD_POOL_EXECUTOR这个线程池去执行这个mActive的Runnable对象。
  • 再次3,如果这时候有第二个任务入队,但是此时mActive!=null,不会执行scheduleNext(),所以如果第一个任务比较耗时,后面的任务都会进入队列等待。
  • 再次4,上面知道由于第二个任务入队后,由于mActive!=null,所以不会执行scheduleNext(),那样这样后面的任务岂不是永远得不到处理,当然不是,因为在offer()方法里面传入一个Runnable的匿名类,并且在此使用了finnally代码,意味着无论发生什么情况,这个finnally里面的代码一定会执行,而finnally代码块里面就是调用了scheduleNext()方法,所以说每当一个任务执行完毕后,下一个任务才会执行。
  • 最后,SerialExecutor其实模仿的是单一线程池的效果,如果我们快速地启动了很多任务,同一时刻只会有一个线程正在执行,其余的均处于等待状态。

PS:scheduleNext()方法是synchronized,所以也是同步的

重点补充:

在Android 3.0 之前是并没有SerialExecutor这个类的,那个时候是直接在AsyncTask中构建一个sExecutor常量,并对线程池总大小,同一时刻能够运行的线程数做了规定,代码如下:

private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,  
        MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); 

四、AsyncTask类的构造函数

代码如下:

    /**
     * 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);
                 // 设定结果变量
                Result result = null;
                try {
                    //设置线程优先级
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    //执行任务
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    // 产生异常则设置失败
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    // 无论执行成功还是出现异常,最后都会调用PostResult
                    postResult(result);
                }
                return result;
            }
        };

        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 occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

通过注释我们知道,这个方法创建一个异步任务,构造函数必须在UI线程调用

这里面设计了两个概念Callable和FutureTask,如果大家对这两个类有疑问,可以看我上一篇文章Android Handler机制12之Callable、Future和FutureTask

构造函数也比较简单,主要就是给mWorker和mFuture初始化,其中WorkerRunnable实现了Callable接口,

在构造函数里面调用了postResult(Result)和postResultIfNotInvoked(Result),那我们就来分别看下

1、postResult(Result)方法
     // doInBackground执行完毕,发送消息
    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        // 获取一个Message对象
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        // 发送给线程
        message.sendToTarget();
        return result;
    }

通过代码我们知道

  • 生成一个Message
  • 把这个Message发送出

这里面调用了 getHandler(),那我们来看下这个方法是怎么写的

2、getHandler()方法
    private static Handler getHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler();
            }
            return sHandler;
        }
    }

我们看到返回的是InternalHandler对象,上面说过了InternalHandler其实是关联主线程的,所以上面方法 message.sendToTarget(); 其实是把消息发送给主线程。

大家注意一下 这里的Message的what值为MESSAGE_POST_RESULT,我们来看下InternalHandler遇到InternalHandler这种消息是怎么处理的

    private static class InternalHandler extends Handler {
        ... 
        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;
               ...
            }
        }
    }

我们看到MESSAGE_POST_RESULT对应的是指是执行AsyncTask的finish(Result)方法,所以我们可以这样说,无论AsyncTask是成功了还是失败了,最后都会执行finish(Result)方法。那我们来看下finish(Result)方法里面都干了什么?

2.1、finish(Result result) 方法
    private void finish(Result result) {
        if (isCancelled()) {
            // 如果消息取消了,执行onCancelled方法
            onCancelled(result);
        } else {
            // 如果消息没有取消,则执行onPostExecute方法
            onPostExecute(result);
        }
        // 设置状态值
        mStatus = Status.FINISHED;
    }

注释写的很清楚了,我这里就不说明了,通过上面的代码和finish方法的分析,我们知道无论成功还是失败,最后一定会调用finish(Result)方法,所以最后状态的值为FINISHED。

3、postResultIfNotInvoked(Result)方法
    private void postResultIfNotInvoked(Result result) {
        // 获取mTaskInvoked的值
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

通过上面代码我们知道,如果mTaskInvoked不为true,则执行postResult,但是在mWorker初始化的时候为true,除非在没有执行call方法时候,如果没有执行call,说明这个异步线程还没有开始执行,这个时候mTaskInvoked为false。而这时候调用postResultIfNotInvoked则还是会执行postResult(Result),这样保证了AsyncTask一定有返回值。

五、AsyncTask类核心方法解析

(一)、void onPreExecute()

    /**
     * Runs on the UI thread before {@link #doInBackground}.
     *
     * @see #onPostExecute
     * @see #doInBackground
     */
     // 在调用doInBackground()方法之前,跑在主线程上
    @MainThread
    protected void onPreExecute() {
    }

其实注释很清楚了,在task任务开始执行的时候在主线程调用,在doInBackground(Params… params) 方法之前调用。

(二)、AsyncTask<Params, Progress, Result> onPreExecute() 方法

    /**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     * 
     * <p>Note: this function schedules the task on a queue for a single background
     * thread or pool of threads depending on the platform version.  When first
     * introduced, AsyncTasks were executed serially on a single background thread.
     * Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
     * to a pool of threads allowing multiple tasks to operate in parallel. Starting
     * {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
     * executed on a single thread to avoid common application errors caused
     * by parallel execution.  If you truly want parallel execution, you can use
     * the {@link #executeOnExecutor} version of this method
     * with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
     * on its use.
     *
     * <p>This method must be invoked on the UI thread.
     *
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
     * @see #execute(Runnable)
     */
    @MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

首先来翻译一下注释

  • 使用指定的参数来执行任务,这个方法的返回值是this,也就是它自己,因为这样设计的目的是可以保持对它的引用。
  • 注意:它的调度模式是不同的,一种是单个后台线程,一种是通过线程池来实现,具体那种模式是根据android版本的不同而不同,当最开始引入AsyncTask的时候,AsyncTask是单个后台线程上串行执行,从Android DONUT 开始,模式变更为通过线程池多任务并行执行。在Android HONEYCOMB开始,又变回了在单个线程上执行,这样可以避免并行执行的错误。如果你还是想并行执行,你可以使用executeOnExecutor()方法并且第一个参数是THREAD_POOL_EXECUTOR就可以了,不过,请注意有关使用警告。
  • 必须在UI主线程上调用此方法。

通过代码我们看到,它的内部其实是调用executeOnExecutor(Executor exec, Params... params)方法,只不过第一个参数传入的是sDefaultExecutor,而sDefaultExecutor是SerialExecutor的对象。上面我们提到了SerialExecutor里面利用ArrayDeque来实现串行的,所以我们可以推测出如果在executeOnExecutor(Executor exec, Params... params)方法里面如果第一个参数是自定义的Executor,AsyncTask就可以实现并发执行。

(三)、executeOnExecutor(Executor exec, Params... params) 方法

    /**
     * Executes the task with the specified parameters. The task returns
     * itself (this) so that the caller can keep a reference to it.
     * 
     * <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
     * allow multiple tasks to run in parallel on a pool of threads managed by
     * AsyncTask, however you can also use your own {@link Executor} for custom
     * behavior.
     * 
     * <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
     * a thread pool is generally <em>not</em> what one wants, because the order
     * of their operation is not defined.  For example, if these tasks are used
     * to modify any state in common (such as writing a file due to a button click),
     * there are no guarantees on the order of the modifications.
     * Without careful work it is possible in rare cases for the newer version
     * of the data to be over-written by an older one, leading to obscure data
     * loss and stability issues.  Such changes are best
     * executed in serial; to guarantee such work is serialized regardless of
     * platform version you can use this function with {@link #SERIAL_EXECUTOR}.
     *
     * <p>This method must be invoked on the UI thread.
     *
     * @param exec The executor to use.  {@link #THREAD_POOL_EXECUTOR} is available as a
     *              convenient process-wide thread pool for tasks that are loosely coupled.
     * @param params The parameters of the task.
     *
     * @return This instance of AsyncTask.
     *
     * @throws IllegalStateException If {@link #getStatus()} returns either
     *         {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
     *
     * @see #execute(Object[])
     */
    @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是先执行,并且在UI线程
        onPreExecute();
        // 设置参数
        mWorker.mParams = params;
        // 开启了后台线程去计算,这是真正调用doInBackground的地方
        exec.execute(mFuture);
        // 接着会有onProgressUpdate会被调用,最后是onPostExecute
        return this;
    }

老规矩 先翻译一下注释:

  • 使用指定的参数来执行任务,这个方法的返回值是this,也就是它自己,因为这样设计的目的是可以保持对它的引用。
  • 这个方法通常与THREAD_POOL_EXECUTOR一起使用,这样可以让多个人物在AsyncTask管理的线程池上并行运行,但你也可以使用自定义的Executor。
  • 警告:由于大多数情况并没有定义任务的操作顺序,所以在线程池中多任务并行并不常见。例如:如果修改共同状态的任务(就像点击按钮就可以编写文件),对修改的顺讯没有保证。在很少的情况下,如果没有仔细工作,较新版本的数据可能会被较旧的数据覆盖,从而导致数据丢失和稳定性问题。而这些变更最好是连续执行,因为这样可以保证工作的有序化,无论平台版本如何,你可以使用SERIAL_EXECUTOR。
  • 必须在UI主线程上调用此方法。
  • 参数exec:为了实现轻松解耦,我们可以使用THREAD_POOL_EXECUTOR这个线程池可以作为合适的进程范围的线程池
  • 参数params:任务的参数

那我们来看下一下代码,代码里面的逻辑如下:

  • 该方法首先是判断mStatus状态,如果是正在运行(RUNNING)或者已经结束(FINISHED),就会抛出异常。
  • 接着设置状态为RUNNING,即运行,执行onPreExecute()方法,并把参数的值赋给mWorker.mParams
  • 于是Executor去执行execute的方法,学过Java多线程的都知道,这里方法是开启一个线程去执行mFuture的run()方法(由于mFuture用Callable构造,所以其实是执行的Callable的call()方法,而mWorker是Callable的是实现类,所以最终执行的是mWorker的call()方法)

PS:mFuture和mWorker都是在AsyncTask的构造方法中初始化过的。

(四)、 publishProgress(Progress... values) 方法

主要是设置后台进度,onProgressUpdate会被调用

    /**
     * This method can be invoked from {@link #doInBackground} to
     * publish updates on the UI thread while the background computation is
     * still running. Each call to this method will trigger the execution of
     * {@link #onProgressUpdate} on the UI thread.
     *
     * {@link #onProgressUpdate} will not be called if the task has been
     * canceled.
     *
     * @param values The progress values to update the UI with.
     *
     * @see #onProgressUpdate
     * @see #doInBackground
     */
    @WorkerThread
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

这个方法内部实现很简单

  • 首先判断 任务是否已经被取消,如果已经被取消了,则什么也不做
  • 如果任务没有被取消,则通过InternalHandler发送一个what为MESSAGE_POST_PROGRESS的Message

这样就进入了InternalHandler的handleMessage(Message)里面了,而我们知道InternalHandler的Looper是Looper.getMainLooper(),所以处理Message是在主线程中,我们来看下代码

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

通过代码,我们看到如果what为MESSAGE_POST_PROGRESS,则会在主线程中调用onProgressUpdate(result.mData),这也就是为什么我们平时在异步线程调用publishProgress(Progress...)方法后,可以在主线程中的onProgressUpdate(rogress... values)接受数据了。

六、AsyncTask核心流程

其实在上面讲解过程中,我基本上已经把整体流程讲解过了,我这里补上一张图,比较全面的阐述了AsyncTask的执行流程如下:

asynctask执行流程.png

对应的时序图如下:

时序图.png

大家如果手机上看不清,我建议down下来在电脑上看。

如果结合AsyncTask的状态值,流程图如下:

流程.png

如果把AsyncTask和Handler分开则流程图如下:

AsyncTask和Handler分开.png

最后如果把AsyncTask里面所有类的涉及关系整理如下图:

20140513095959437.jpeg

七、AsyncTask与Handler

  • AsyncTask:
    • 优点:AsyncTask是一个轻量级的异步任务处理类,轻量级体现在,使用方便,代码简洁,而且整个异步任务的过程可以通过cancel()进行控制
    • 缺点:不适用处理长时间的异步任务,一般这个异步任务的过程最好控制在几秒以内,如果是长时间的异步任务就需要考虑多线程的控制问题;当处理多个异步任务时,UI更新变得困难。
  • Handler:
    • 优点:代码结构清晰,容易处理多个异步任务
    • 缺点:当有多个异步任务时,由于要配合Thread或Runnable,代码可能会稍显冗余。

总之,AsyncTask不失为一个非常好用的异步任务处理类。不过我从事Android开发5年多了,很少会用到AsyncTask,一般异步任务都是Handler。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容