Android多线程(二)AsyncTask源码分析

最后更新于:2022-04-01 14:46:05

转载请注明出处:[](http://blog.csdn.net/guolin_blog/article/details/42238633)[http://blog.csdn.net/itachi85/article/details/45041923](http://blog.csdn.net/itachi85/article/details/45041923) AsyncTask的基本用法这里就不在赘述了,是个安卓开发者就会。 **1.android 3.0以前的 AsyncTask** ~~~ private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 128; private static final it KEEP_ALIVE = 10; …… private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); ~~~ 在这里我们又看到了ThreadPoolExecutor,它的原理我已经在上一篇介绍过了[http://blog.csdn.net/itachi85/article/details/44874511](http://blog.csdn.net/itachi85/article/details/44874511)。 在这里同一时刻能够运行的线程数为5个,线程池总大小为128,当线程数大于核心时,终止前多余的空闲线程等待新任务的最长时间为10秒。在3.0之前的AsyncTask可以同时有5个任务在执行,而3.0之后的AsyncTask同时只能有1个任务在执行。 **2.让我们来看看android 4.3版本的 AsyncTask** AsyncTask构造函数: ~~~ /** * 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); 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和mFuture,并在初始化mFuture的时候将mWorker作为参数传入。mWorker是一个Callable对象,mFuture是一个FutureTask对象,这两个变量会暂时保存在内存中,稍后才会用到它们。 我们要运用AsyncTask时,大多时候会调用execute()方法,来看看execute()的源码: ~~~ public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params);} ~~~ 返回了executeOnExecutor并传进去sDefaultExecutor(默认的线程池)。先看看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; } ~~~ 传入的线程池exec调用了execute方法并将上文提到的mFuture传了进去。 这个传进来的线程池sDefaultExecutor就是默认的线程池SerialExecutor也就是调用了SerialExecutor的execute()方法: ~~~ public static final Executor SERIAL_EXECUTOR = new SerialExecutor(); private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR; ~~~ 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); } } } ~~~ 调用SerialExecutor的execute方法这里可以看到传进来一个Runnable,这个Runnable就是上文提到的mFuture(FutureTask),第九行执行了FutureTask的run方法: ~~~ public void run() { if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; try { Callable<V> c = callable; if (c != null && state == NEW) { V result; boolean ran; try { result = c.call(); ran = true; } catch (Throwable ex) { result = null; ran = false; setException(ex); } if (ran) set(result); } } finally { // runner must be non-null until state is settled to // prevent concurrent calls to run() runner = null; // state must be re-read after nulling runner to prevent // leaked interrupts int s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } } ~~~ 在run方法中执行了c.call,这里的c就是我们上文提到的mWorker(WorkerRunnable)。执行WorkerRunnable的call方法: ~~~ 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)); } ~~~ 最后一行postResult()方法源码: ~~~ private Result postResult(Result result) { @SuppressWarnings("unchecked") Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result)); message.sendToTarget(); return result; } ~~~ 我们发现就是发送了一个消息,上面的代码发送的消息由这里接受: ~~~ 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; } } } ~~~ 消息是MESSAGE_POST_RESULT所以会执行 result.mTask.finish(result.mData[0])  ,finish源码: ~~~ private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } ~~~ 当被取消时会执行 onCancelled(result);否则就会调用 onPostExecute(result);这样我们就可以在onPostExecute方发中得到我们需要的结果result来进行下一步的处理了。 **3.AsyncTask中的线程池 ** AsyncTask中一共定义了两个线程池一个是此前我们已经介绍了线程池SerialExecutor,这个是目前我们调用AsyncTask.execute()方法默认使用的线程池,这个在前一篇文章中已经讲到过了,另一个是3.0版本之前的默认线程池THREAD_POOL_EXECUTOR。现在我们来回顾一下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(); } } ~~~ 这个默认的线程池同一时间只能处理一个任务,一个任务完成以后才可以执行下一个任务,相当于Executors.newSingleThreadPool()。上面的arrayDeque是一个装载Runnable的队列,如果我们一次性启动了很多个任务,在第一次运行execute()方法的时候会调用ArrayDeque的offer()方法将传入的Runnable对象添加到队列的尾部, 然后判断mActive对象是不是等于null,第一次运行等于null,于是调用scheduleNext()方法。另外在finally中也调用了scheduleNext()方法,这样保证每次当一个任务执行完毕后,下一个任务才会执行。我们来看看scheduleNext()方法的源码: ~~~ protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } ~~~ 首先从runnable队列的头部取值,如果不为空就赋值给mActive对象,然后调用THREAD_POOL_EXECUTOR去执行取出的Runnable对象。THREAD_POOL_EXECUTOR源码: ~~~ private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 128; private static final int KEEP_ALIVE = 1; . public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); ~~~ 这是3.0版本之前的线程池,同一时刻能够运行的线程数为5个,workQueue总大小为128。当我们启动10个任务,只有5个任务能够优先执行,其余的任务放在workQueue中,当workQueue大于128时就会调用RejectedExecutionHandler来做拒绝处理。当然在3.0之前是并没有SerialExecutor这个类的。如果不希望用默认线程池我们也可以使用这个3.0版本之前的线程池 ~~~ AsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null); ~~~ 同时3.0版本也提供了executeOnExecutor这个方法可以传入AsyncTask定义的线程池也可以传入Executor定义的4种线程池,不知道这四种线程池的可以看[http://blog.csdn.net/itachi85/article/details/44874511](http://blog.csdn.net/itachi85/article/details/44874511) 传入CachedThreadPool: ~~~ LikeListTask mLikeListTask=new LikeListTask(); executeOnExecutor(Executors.newCachedThreadPool(), null); ~~~ 当然我们也可以传入自定义的线程池: ~~~ Executor exec =new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); new LikeListTask().executeOnExecutor(exec, null); ~~~ 我们看到这里定义的是一个类似于CachedThreadPool的一个线程池
';