AsyncTask源码分析(Android7.0)

ggtx2404 8年前
   <h3><strong>1.Android 3.0版本之前的AsyncTask</strong></h3>    <p>下面是Android 2.3.7版本的AsyncTask的部分源码。</p>    <pre>  <code class="language-java">public abstract class AsyncTask<Params, Progress, Result> {    private static final String LOG_TAG = "AsyncTask";    private static final int CORE_POOL_SIZE = 5;    private static final int MAXIMUM_POOL_SIZE = 128;    private static final int KEEP_ALIVE = 1;    private static final BlockingQueue<Runnable> sWorkQueue =             new LinkedBlockingQueue<Runnable>(10);    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 ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,              MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);      ...           }</code></pre>    <p>在这里又看到了ThreadPoolExecutor,它的核心线程数是5个,线程池允许创建的最大线程数为128,非核心线程空闲等待新任务的最长时间为10秒。采用的阻塞队列是LinkedBlockingQueue,它的容量为10。3.0版本之前的AsyncTask有一个缺点就是,线程池最大的线程数为128,加上阻塞队列的10个任务,所以AsyncTask最多能同时容纳138个任务,当提交第139任务时就会执行饱和策略,默认抛出RejectedExecutionException异常。</p>    <h3><strong>2.Android 7.0版本的AsyncTask</strong></h3>    <p>在这里采用Android 7.0版本的AsyncTask作为例子,首先来看AsyncTask的构造函数:</p>    <pre>  <code class="language-java">public AsyncTask() {      mWorker = new WorkerRunnable<Params, Result>() {//1          public Result call() throws Exception {              mTaskInvoked.set(true);              Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);              Result result = doInBackground(mParams);              Binder.flushPendingCommands();              return postResult(result);          }      };        mFuture = new FutureTask<Result>(mWorker) {//2          @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);              }          }      };  }</code></pre>    <p>从注释1处看这个WorkerRunnable实现了Callable<Result>接口,并实现了它的call方法,在call方法中调用了doInBackground(mParams)来处理任务并得到结果,并最终调用postResult将结果投递出去。注释2处的FutureTask是一个可管理的异步任务,它实现了Runnable和Futrue这两个接口。因此它可以包装Runnable和Callable<V>,并提供给Executor执行。也可以调用线程直接执行(FutureTask.run())。在这里WorkerRunnable作为参数传递给了FutureTask。这两个变量会暂时保存在内存中,稍后会用到它们。</p>    <p>当要执行AsyncTask时,需要调用它的execute方法,代码如下所示。</p>    <pre>  <code class="language-java">public final AsyncTask<Params, Progress, Result> execute(Params... params) {          return executeOnExecutor(sDefaultExecutor, params);      }</code></pre>    <p>execute方法又调用了executeOnExecutor方法:</p>    <pre>  <code class="language-java">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;//1          exec.execute(mFuture);          return this;      }</code></pre>    <p>这里会首先调用 onPreExecute方法,在注释1处将AsyncTask的参数传给WorkerRunnable,从前面我们知道WorkerRunnable会作为参数传递给了FutureTask,因此,参数被封装到FutureTask中。接下来会调用exec的execute方法,并将mFuture也就是前面讲到的FutureTask传进去。这里exec是传进来的参数sDefaultExecutor,它是一个串行的线程池,它的代码如下所示。</p>    <pre>  <code class="language-java">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() {//1                  public void run() {                      try {                          r.run();//2                      } finally {                          scheduleNext();                      }                  }              });              if (mActive == null) {                  scheduleNext();              }          }          protected synchronized void scheduleNext() {              if ((mActive = mTasks.poll()) != null) {                  THREAD_POOL_EXECUTOR.execute(mActive);              }          }      }</code></pre>    <p>从注释1处可以看出,当调用SerialExecutor 的execute方法时,会将FutureTask加入到mTasks中。当任务执行完或者当前没有活动的任务时都会执行scheduleNext方法,它会从mTasks取出FutureTask任务并交由THREAD_POOL_EXECUTOR处理。关于THREAD_POOL_EXECUTOR,后面会介绍。从这里看出SerialExecutor是串行执行的。在注释2处可以看到执行了FutureTask的run方法,它最终会调用WorkerRunnable的call方法。</p>    <p>前面我们提到call方法postResult方法将结果投递出去,postResult方法代码如下所示。</p>    <pre>  <code class="language-java">private Result postResult(Result result) {          @SuppressWarnings("unchecked")          Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,                  new AsyncTaskResult<Result>(this, result));          message.sendToTarget();          return result;      }</code></pre>    <p>在postResult方法中会创建Message,并将结果赋值给这个Message,通过getHandler方法得到Handler,并通过这个Handler发送消息,getHandler方法如下所示。</p>    <pre>  <code class="language-java">private static Handler getHandler() {      synchronized (AsyncTask.class) {          if (sHandler == null) {              sHandler = new InternalHandler();          }          return sHandler;      }  }</code></pre>    <p>在getHandler方法中创建了InternalHandler,InternalHandler的定义如下所示。</p>    <pre>  <code class="language-java">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;              }          }      }</code></pre>    <p>在接收到MESSAGE_POST_RESULT消息后会调用AsyncTask的finish方法:</p>    <pre>  <code class="language-java">private void finish(Result result) {      if (isCancelled()) {          onCancelled(result);      } else {          onPostExecute(result);      }      mStatus = Status.FINISHED;  }</code></pre>    <p>如果AsyncTask任务被取消了则执行onCancelled方法,否则就调用onPostExecute方法。而正是通过onPostExecute方法我们才能够得到异步任务执行后的结果。</p>    <p>接着回头来看SerialExecutor ,线程池SerialExecutor主要用来处理排队,将任务串行处理。 SerialExecutor中调用scheduleNext方法时,将任务交给THREAD_POOL_EXECUTOR。THREAD_POOL_EXECUTOR同样是一个线程池,用来执行任务。</p>    <pre>  <code class="language-java">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 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;      }</code></pre>    <p>THREAD_POOL_EXECUTOR指的就是threadPoolExecutor,他的核心线程和线程池允许创建的最大线程数都是由CPU的核数来计算出来的。它采用的阻塞队列仍旧是LinkedBlockingQueue,容量为128。</p>    <p>到此, Android 7.0版本的AsyncTask的源码就分析完了,在AsyncTask中用到了线程池,线程池中运行线程并且又用到了阻塞队列,因此,本章前面介绍的知识在这一节中做了很好的铺垫。Android 3.0及以上版本用SerialExecutor作为默认的线程,它将任务串行的处理保证一个时间段只有一个任务执行,而3.0之前版本是并行处理的。关于3.0之前版本的缺点在3.0之后版本也不会出现,因为线程是一个接一个执行的,不会出现超过任务数而执行饱和策略。如果想要在3.0及以上版本使用并行的线程处理可以使用如下的代码:</p>    <pre>  <code class="language-java">asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");</code></pre>    <p>其中asyncTask是我们自定义的AsyncTask,当然也可以传入Java提供的线程池,比如传入CachedThreadPool。</p>    <pre>  <code class="language-java">asyncTask.executeOnExecutor(Executors.newCachedThreadPool(),"");</code></pre>    <p>也可以传入自定义的线程池:</p>    <pre>  <code class="language-java">Executor exec =new ThreadPoolExecutor(0,  Integer.MAX_VALUE,                  0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());     asyncTask.executeOnExecutor(exec,"");</code></pre>    <p> </p>    <p>来自:http://www.jianshu.com/p/ed7d9fb724cf</p>    <p> </p>