Android AsynTask 实现原理
从外部启动调用AsyncTask, 通过调用execute方法。
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;
}
这个方法必须是在主线程(UI thread)中运行.
这个方法可以用自定义的Executor,达到多个线程同时执行。
1. 方法首先是判断当前任务的状态;
2. 然后执行
onPreExecute()方法, 这个方法是空的, 如果用户重写了该方法,那么一般是些初始化的操作。 3. 然后把params参数传递给Callback类(Class:WorkerRunnable)的成 员变量mParams;这个参数会用到
FuthurTask中。
4.exec默认的情况下其实是
SerialExecutor
5.返回自己
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);
}
}
}