AsyncTask源码分析

说到Android中的异步执行AsyncTask一定不陌生,今天就让我们来到它的内部一探究竟。

首先简单写一个使用例子:
定义一个异步任务

private class MyAsyncTask extends AsyncTask<String, Integer, String> {

    @Override
    protected void onPreExecute() {
      super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
      return null;
    }

    @Override
    protected void onPostExecute(String s) {
      super.onPostExecute(s);
    }

  }

执行该任务

new MyAsyncTask().execute("");

我们从任务的起点execute()看起:

    @MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

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

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }

可以看到这个方法必须在主线程中调用,方法中对状态过了一个过滤和变更,回调onPreExecute方法让我们在任务执行前进行一些操作。里面涉及到了2个关键变量mWorkermFuture
它们都是在构造函数那进行初始化:

public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

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

可以看到mWorkerWorkerRunnable的实例,而它实现了Callable<Result>接口,并在call()方法中调用了doInBackground来处理任务并获取结果,最终通过postResult方法将结果送出:

   private Result postResult(Result result) {
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

还是那个熟悉的套路,通过Handler进行消息的发送,那么必须会有一个地方来进行消息的处理:

   private static class InternalHandler extends Handler {
        public InternalHandler(Looper looper) {
            super(looper);
        }

        @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;
            }
        }
    }
   private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

收到消息并在处理完毕后变更任务状态,将任务的处理结果回调出去。
而变量mFuture,它是FutureTask的实例,FutureTask是一个可取消的异步任务,它实现了RunnableFuture接口,并且可以包装CallableRunnable对象然后交由Executor执行。这里WorkerRunnable作为参数被包装进了FutureTask

那么我们回过头来看看exec.execute(mFuture)方法:

private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

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

这里exec其实就是sDefaultExecutor,它是一个串行的线程池。当我们调用execute方法时,就会将上面提到了FutureTask加入到mTasks中。当任务执行完或者没有任务的时候就会执行scheduleNext方法,从mTasks中取出任务并交由THREAD_POOL_EXECUTOR进行处理。

关于THREAD_POOL_EXECUTOR

    //CPU核数
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
   //线程池核心线程数
    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);

    public static final Executor THREAD_POOL_EXECUTOR;

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

可以看到THREAD_POOL_EXECUTOR是一个线程池,也是AsyncTask真正的执行者。
如果想要实现并行效果,我们可以通过调用public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params),定义一个并行执行的Executor即可。
至此便是AsyncTask所有的执行流程。

版权声明:

本文标题:AsyncTask源码分析

作者:Rabtman

原始链接:https://rabtman.com/2017/06/10/asynctask_source/

本文采用署名-非商业性使用-禁止演绎4.0进行许可。

非商业转载请保留以上信息。商业转载请联系作者本人。