在UI线程中要执行耗时操作时,我们可以使用AsyncTask进行异步操作,使耗时的异步操作可以在子线程中进行,最后将执行结果返回给UI线程,下面来看下AsyncTask的源码。
首先来看下,AsyncTask的变量和常量:
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 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 = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
可以可看出AsyncTask首先使用了CUP的核数等信息构建了一个线程池,并赋给常量THREAD_POOL_EXECUTOR。继续接下来的代码:
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
这里实例化一个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); } } }
这个类实现了Executor,也是个线程词,但这个线程词有点特殊,内部使用了ArrayDeque队列来保持要准备执行的Runnable,如果一下子来了多个Runnable,这些Runnable会按顺序进入队列中,但第一个要执行时,会发现mActive = null,就会执行 scheduleNext里面的代码。在scheduleNext方法中,会从队列取第一个Runnable,并且交给上面定义的线程池 THREAD_POOL_EXECUTOR去执行,这时候就会执行r.run()了,但要注意的是,当r.run()执行完之后,才会继续执行 scheduleNext()方法,所以可以看出在SerialExecutor这个线程词中的Runnable其实是按顺序执行了,只要当上一个执行完了,下一个才开始执行。接下去看源码:
private staticvolatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
这时将SERIAL_EXECUTOR赋值给了sDefaultExecutor这个变量。看完这些我们就可以看看,我们用的execute(Params... params)方法了:
public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); }
很简单,调用了executeOnExecutor,继续跟踪:
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; }
首先判断了当前的状态了,如果为RUNNING或者FINISHED就抛异常,所以可以看出AsynTask只能执行一次,接下来执行了onPreExecute()做些准备工作,接下去为
mWorker.mParams = params;
exec.execute(mFuture);
这里出现了mWorker和mFuture,先看下mWorker的定义:
private final WorkerRunnable<Params, Result> mWorker;
是WorkerRunnable类型,看下代码:
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> { Params[] mParams; }
在来看下mFuture的变量,private final FutureTask<Result> mFuture;其实是一个FutureTask。
倒数第二行代码 exec.execute(mFuture);中的exec就是sDefaultExecutor,也就是SerialExecutor。
好了,那么mWorker和mFuture在什么地方被赋值的呢,可以看下AsynTask的构造方法:
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); } } }; }
在构造方法中,对mWorker进行了实例化,因为WorkerRunnable是抽象类,重写了其中的call方法,并定义了该方法线程优先级为后台线程,之后就会调用了我们期待的doInBackground方法,并将doInBackground返回的Result作为参数传给postResult方法。
而mFuture是一个FutureTask抽象类,并以mWorker作为参数,在mWorker中的call方法执行完成之后,会调用FutureTask中的done()方法,done()方法中调用了
postResultIfNotInvoked(get()),看下代码:
private void postResultIfNotInvoked(Result result) { final boolean wasTaskInvoked = mTaskInvoked.get(); if (!wasTaskInvoked) { postResult(result); } }
由于wasTaskInvoked在mWorker中的call方法执行时赋值了true,所以这里的postResultIfNotInvoked其实很少执行的。
现在来看下mWorker中调用的postResult,他以doInBackground运行结果作为参数,源码如下:
private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; }
这里出现了一个sHandler,并从这个Handler获取了一个Message,以MESSAGE_POST_RESULT常量和一个AsyncTaskResult作为参数放送出去。先看下AsyncTaskResult是什么东西:
@SuppressWarnings({"RawUseOfParameterizedType"}) private static class AsyncTaskResult<Data> { final AsyncTask mTask; final Data[] mData; AsyncTaskResult(AsyncTask task, Data... data) { mTask = task; mData = data; } }
AsyncTaskResult的作用就是对AsyncTask和Result进行封装。回来,看下sHandler:
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; } } }
注意在声明Handler过程并未出现过什么Looper相关的,也是就是InternalHandler只能声明在UI线程中,所以AsynTask只能在UI线程中进行声明。看handleMessage方法,首先会从msg中取出AsyncTaskResult,之后调用
result.mTask.finish(result.mData[0])对Result进行处理(doInBackground返回的Result最终通过Handler会传到这里),看下finish方法:
private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; }
这里先判断了,是否当前的Task是否被取消了,如果没有就将Result给我们经常重写的 onPostExecute(result)方法了,最后将当前状态标记为FINISHED,这个AsynTask差不多到这就结束咯。
原文地址:http://blog.csdn.net/yifei1989/article/details/44175567