AsyncTask源码阅读

2019-05-15  本文已影响0人  坠叶飘香

1.AsyncTask的三个泛型Params,Progress和Result

2.AsyncTask

public abstract class AsyncTask<Params, Progress, Result> {
  //一个AsyncTask持有
 //volatile关键字
  private volatile Status mStatus = Status.PENDING;

  //原子
  private final AtomicBoolean mCancelled = new AtomicBoolean();
  private final AtomicBoolean mTaskInvoked = new AtomicBoolean();

  //所有AsyncTask共用
  //static
  //volatile   
  private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
  public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
}

3.AsyncTask的启动执行过程

3.1 AsyncTask构造方法里面,初始化了mWorker和mFuture这两个重要的变量

mWorker的call方法里执行 doInBackground方法,然后在finally里面调用postResult方法,这样onPostExecute和onProgressUpdate会被调用,整个AsyncTask的执行就完成了。

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) { //这里其实将mWorker赋值给了mFuture的callable这个成员变量
    @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);
       }
      }
    };
}
3.2 execute方法

sDefaultExecutor:是一个static volatile 的Executor ,说明一个应用所有的AsyncTask共用它。

private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
  return executeOnExecutor(sDefaultExecutor, params);
}
3.3 executeOnExecutor
@MainThread
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,Params... params) {
  //如果mStatus已经处于RUNNING或者FINISHED状态,则会抛出相应异常
  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)");
      }
    }
    //设置状态为RUNNING
    mStatus = Status.RUNNING;

    //执行onPreExecute
    onPreExecute();

    //设置参数
    mWorker.mParams = params; 
    exec.execute(mFuture); //让sDefaultExecutor来管理执行

    return this;
}
3.4. mFuture的run方法
public void run() {
  if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread()))
    return;
  try {
    Callable<V> c = callable;       //mWorker
    if (c != null && state == NEW) {
      V result;
      boolean ran;
      try {
        result = c.call();  //触发mWorker的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);
    }
}
3.5 mWorker的call方法最后会调用postResult方法
通过sHandler切换主线程
private Result postResult(Result result) {
  @SuppressWarnings("unchecked")
  Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>(this, result));
  message.sendToTarget();
  return result;
}
3.6 sHandler会根据得到的msg.what调用不同方法
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:  //更新progress
        result.mTask.onProgressUpdate(result.mData);
      break;
    }
  }
}
3.7 finish中调用onPostExecute方法
private void finish(Result result) {
  if (isCancelled()) {
    onCancelled(result);
  } else {
    onPostExecute(result);
  }
  mStatus = Status.FINISHED; //更新状态为FINISHED
}

4. 单例模式

sHandler是全局静态变量
private static InternalHandler sHandler;
private static Handler getHandler() {
  synchronized (AsyncTask.class) {
    if (sHandler == null) {
      sHandler = new InternalHandler();
    }
    return sHandler;
  }
}

5.SerialExecutor 默认的Executor

如果执行AsyncTask的execute()方法,会使用SerialExecutor,那样execute方法会将每个AsyncTask的mFuture放入mTasks,mTasks会按顺序一个一个执行。
mFuture执行
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);
      }
    }
}
上一篇下一篇

猜你喜欢

热点阅读