AsyncTask 源码解析

AsyncTask 是android里线程的使用方式之一,优点在于简单易用。它封装处理了异步消息处理,即Handler的使用方式。 AsyncTask保证线程操作处于后台线程,而在后台操作的前后,能在UI线程操作中使用AsyncTack执行相关的UI操作。AsyncTask是个抽象类,需要子类实例化使用。 下面是源码:

protected abstract Result doInBackground(Params... params);
protected void onPreExecute() {}
protected void onPostExecute(Result result) {}
protected void onProgressUpdate(Progress... values) {}

首先,是AsyncTask重要的四个函数

1、onPreExecute()运行在doInBackground() , 为线程的执行进行准备工作
2、doInBackground()执行我们所需要的线程工作
3、onProgressUpdate()可以在doInBackground()中通过publishProgress()调用, 可以根据线程的执行进度做相应的操作,如跟新进度条
4、onPostExecute()在doInBackground()运行结束后调用,处理我们在doInBackground()中获得的结果

从注释上可以知道(注释已省略没有加进来),doInBackground()方法运行在后台线程,而其他三者运行在UI线程。 那么doInBackground()是否真的是运行在后台线程呢? 别着急,下面会有解答。

public abstract class AsyncTask<Params, Progress, Result> {

    ......

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

    /**
     * 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 volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

    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的时候,需要提供个参数,第一个是一组不定个数的参数Params,在doInBackground()中使用,第二参数Progress可在onProgressUpdate()中使用,第三个参数Result,将在onPostExecute()中使用。再看AsyncTask,它维护两个线程池 —— THREAD_POOL_EXECUTOR 和 SERIAL_EXECUTOR , 从注释中可看到前者在并行时使用, 而后者做为默认情况下为默认线程池(运行方式为串行)。 在此注意一点,AsyncTask不建议使用并行操作,除非很了解如何安全地并行,因为AsyncTask不保证并行安全性。因此,此处谈SERIAL_EXECUTOR 。

SERIAL_EXECUTOR 在执行时,不断从队列mTasks取出线程然后执行,在线程执行结束或因其他原因终止后,继续从mTasks取出线程然后执行,可见scheduleNext(),重复此过程。

接下来是AsycnTask的构造过程

    /**
     * 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(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);
                }
            }
        };
    }
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

AsyncTask在构造的时候,实例化工作线程WorkerRunnable,WorkerRunnable为内部类。见call()中,此WorkerRunnable将线程设置在运行在后台,然后执行doInBackground(mParams),在此就解答了前面的疑问,即doInBackground()运行在后台线程。在doInBackground()执行完毕后,返回参数Resulet。

private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

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

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

工作线程,和FutureTask的执行,都会执行到postResult() ,将result发送出去, 而postResult() 将result封装到了Message,发送到了Handler,见getHandler()。

什么?发送到了Hanlder?没错,还记得我们说过AsyncTack封装了异步消息吗,也就是封装处理了Handler的异步消息使用,那么,我们有必要看看InternalHandler。

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

可见InternalHandler 在接收到消息后,会根据消息的不同调用不同的函数handleMessage()是执行在UI线程里的,这里就解决了异步消息问题。

onProgressUpdate() , 有点眼熟,它好像是我们四个重要的函数之一,那么是不是就是说,mTask保存的是当前AsyncTask的引用? 我们来看看AsyncTaskResult

private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

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

果然,AsyncTaskResult 是 AsyncTask的内部类,它引用了当前AsyncTask自身

在此就明了,利用HanlderMessage运行在UI线程,保证AsyncTask的一些函数可以运行在UI线程里。也就是对Handler进行了封装

那finish()是什么?

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

同样的,finish()先检查AsyncTask是否被取消。 onPostExecute()也是在这里,可能被调用,同样会运行在UI线程

我们前面的出发点postResult()发送的result,在finish()接收到了,然后传递给了onPostExecute()

此外,通过在doInBackground()中调用publishProgress() 向InternalHandler发送消息调用onProgressUpdate()

protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

也是和前面的result一样,此函数将values封装到Message里,发送到了InternalHandler 。 主要流程一样,在此不多说。

在所有对于AsyncTask的准备工作完成后,就到了AsyncTask的执行

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

AsyncTask有两种执行方式,最终都会调用到executeOnExecutor() ,区别在于execute()是使用推荐使用的默认线程池SERIAL_EXECUTOR执行线程,而executeOnExecutor()则可以使用自定义的线程池执行并行操作。

AsyncTask的解析到此也差不多结束,下面是executeOnExecutor()的运行,也是对AsyncTask的总结

1、在AsyncTask的执行中,首先会检查自身状态mStatus ,根据自身状态抛出异常,即AysncTask不允许重复调用执行,也不允许在结束后调用。
2、 接着,执行onPreExecute() , 做准备工作
3、执行FutureTask,FutureTask执行工作线程WorkerRunnable(在构造函数时,已实现FuctureTask和WorkerRunnable的相应函数),工作线程在后台运行doInBackground()
4、在doInBackground()运行期间,可以通过publishProgress()方法调用onProgressUpdate()处理阶段性事项
5、在doInBackground()执行完毕后,传递结果给onPostExecute(),在onPostExecute()中根据最终结果执行相应操作

注意:在使用AsyncTask时需事先doInBackground()方法,其他三个重要方法根据需要覆盖。

在此,顺便提及

public static void execute(Runnable runnable) {
        sDefaultExecutor.execute(runnable);
    }

AsyncTask支持简单地执行线程操作。

此博客为个人学习笔记,如有不足,欢迎指出,感激不尽

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值