AsyncTask源码分析

Awara 2013-11-25

       在android开发中,如果有比较耗时的操作,为了避免ANR,我们一般采用多线程的方式来运行耗时操作。而android推荐我们使用AsyncTask来启动新的线程,根据API文档的介绍,我们知道AsyncTask在耗时任务执行完毕后能直接更新UI线程,所以使用这个类可以满足我们大多数的多线程开发需求。但是这个工具类的底层实现是怎样的?下面我们通过阅读源码来研究一下。通过阅读源码,得知AsyncTask在实现上不是直接使用Thread类,而是使用了JDK5引入的并发包里执行器(Executor)来启动线程。首先从AsyncTask类的入口方法execute(Params... params)开始跟踪代码。

       

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

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

       可以看到在execute方法中直接调用了executeOnExecutor(sDefaultExecutor, params)方法,最终执行到sDefaultExecutor的execute方法。可见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);
            }
        }
    }

       可以看到,AsyncTask类默认的执行器是串行执行器。这里的串行是指提交到AsyncTask类的Runnable都是串行执行的。当执行到SerialExecutor 的Executor方法时,并不是立即运行该Runnable,而是重新包装一下该Runnable(该Runnable运行结束后自动执行双向队列里面的下一个Runnable),并把包装后的Runnable添加到双向队列中。这样做的好处是可以避免并发所带来的常见问题。如果不想采用串行的方式,可以通过setDefaultExecutor(Executor exec)来传入自己的执行器。真正对Runnable的执行是在scheduleNext方法中,通过THREAD_POOL_EXECUTOR来真正的执行提交到AsyncTask的任务。其中:

   

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

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE = 1;
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);

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

       根据ThreadPoolExecutor构造函数里面的参数,可以看出该线程池常驻线程为(CPU_COUNT + 1)个,最多允许(CPU_COUNT * 2 + 1)个线程存在,多余的空闲线程的存活时间为1秒,保存未执行的task是一个阻塞队列,sThreadFactory 负责创建新线程。

       接下来,我们分析下mFuture。通过阅读源码得知,mFuture的初始化是在AsyncTask类的构造方法中执行的。

public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

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

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

       到这里为止,整个AsyncTask类的执行流程就清晰了。先是在AsyncTask类的构造方法中初始化mFuture,当执行到exec.execute(mFuture)时会执行mFuture的run方法,在run方法中调用mWorker的call方法,而在call方法中会最终执行我们在doInBackground中实现的操作,并返回Result,返回后再通过Handler来更新UI,其中:

private static final InternalHandler sHandler = new InternalHandler();
    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;
            }
        }
    }

          至此,AsyncTask的源码已基本分析完毕。有什么不对的地方,欢迎大家指正。

相关推荐