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);
}
}
}