AsyncTask 工作原理(下)

569 阅读4分钟

本文主要是根据AsyncTask 源码进一步对 AsyncTask 异步任务有更深入的理解

AsyncTask执行

new AsynTask().execute()

我们从AsyncTask的execute()方法开始 来分析AsyncTask的工作原理

源码分析

public final AsyncTask execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

通过上述代码我们可以看到 在execute方法中执行了 executeOnExecutor方法,该方法executeOnExecutor中的两个参数

参数一:sDefaultExecutor 通过代码可以看出

 public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

该参数是AsyncTask 内部的一个线程池

参数二: Params… params 为AsyncTask 执行exexute方法时传入的参数;

接下来我们只需要分析 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();
        mWorker.mParams = params;
        exec.execute(mFuture);
        return this;
    }

通过代码中我们可以看到AsyncTask会先根据任务的状态进行判断,只有当该任务为PENDING 状态时,才能够继续执行。
通过该判断我们可以看出:
一个AsyncTask 对象只能执行一次,即只能调用一次execute方法,否则会报运行时异常。
*注:通过android5.0源码 ActivityThread的main方法中对AsyncTask 进行了初始化,这就表示AsyncTask
类必须在主线程中加载,同时execute方法必须在主线程中调用;*

接下来我们可以看到mSattus 状态值的改变,以及内部调用了 onPreexecute() 方法。因为execute方法必须在主线程中调用,由此可以看出 onPreExecute方法是在主线程中被调用的。

  protected void onPreExecute() {
    }

而我们通过源码可以看出 onPreExecute 方法是一个空实现。因此外部通过重写该方法,在异步任务执行之前初始化一些基础数据。但由于该方法是运行在主线程中,切勿进行一些耗时操作。

我们继续往下看 可以看出 有外部传入的params 复制给了 mWorker.mParams ,mWorker在AsyncTask中表示WorkerRunnable ,WorkerRunnable 则是AsyncTask 中的内部抽象类。

 private final WorkerRunnable mWorker;

private static abstract class WorkerRunnable implements Callable {
        Params[] mParams;
    }

注:Callbale 代码

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

在params 赋值之后,我们可以看到 真正的AsyncTask的执行是通过

 exec.execute(mFuture);
public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

代码开始的。

exec : 线程池 new SerialExecutor()对象
mFuture: Runnable 对象

通过AsyncTask 源码中可以看出 mFuture

 private final FutureTask mFuture; 

是 FutureTask 对象,而

public class FutureTask implements RunnableFuture

是一个Runnable的实现类

AsyncTask 实现了一个内部类

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

该内部类实现了 Executor 接口,所以当
exec.execute(mFuture); 方法执行时,调用了AsyncTask 的内部类 SerialExecutor的execute 方法
该方法中有进一步调用了

mTasks.offer()

  /**
     * Inserts the specified element at the end of this deque.
     *
     * 

This method is equivalent to {@link #offerLast}. * * @param e the element to add * @return true (as specified by {@link Queue#offer}) * @throws NullPointerException if the specified element is null */ public boolean offer(E e) { return offerLast(e); }

而offer 方法的说明是 将元素添加到deque的 end位置。

通过offer方法 实际是将 FutureTask 对象一次添加到 ArrayDeque 队列中去,当添加完成之后

如果此时没有正在活动的AsyncTask 则会调用 scheduleNext()方法 来执行下一个AsyncTask,

同时当一个AsyncTask 执行完成之后,AsyncTask 会继续执行其他任务,直到所有任务被执行完成。

通过scheduleNext(); 内部实现可以看出AsyncTask 是顺序取出 ArrayDeque 队列中的 mFutufre 并执行
THREAD_POOL_EXECUTOR.execute(mActive);方法

 public static final Executor THREAD_POOL_EXECUTOR
            = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                    TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

可以看出 THREAD_POOL_EXECUTOR 为一个线程池。

由此可以看出 SerialExecutor 线程池是负责将FutureTask添加到 ArrayDeque 对列中去,而THREAD_POOL_EXECUTOR 才是 真正的执行任务。

而FutureTask 的run方法 最终会调用到 WorkerRunnable 的call 方法

接下来我们只需要看 WorkerCallRunnable 中的call方法即可

 mWorker = new WorkerRunnable() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

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

很明显在call方法中调用了 doInBackground(mParams) 并将其其返回值传给了 postResult 方法

而postResult方法 中

private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult(this, result));
        message.sendToTarget();
        return result;
    }

通过Message 发送了一条消息,消息的接受者是

private static InternalHandler sHandler;

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

可以看到 接受到消息之后,调用了 finish方法,现在我们只需要看finish方法

finish源码

  private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

由此可以看出 finish中 如果isCancelled为true 则不会调用onPostExecute 方法,如果为false 则调用onPostExecute 方法。

至此AsyncTask 异步任务分析完成,有不正确的地方请各位大神指出。