內部封裝了2個線程池+1個Handler(InternalHandler),1個線程池SerialExecutor任務排隊,一個線程池THREAD_POOL_EXECUTOR執行任務。bash
public class MyTask extends AsyncTask<String, Double, Float> {
@Override // 子線程執行任務
protected Float doInBackground(String... strings) {
publishProgress(5D);
return 1f;
}
@Override // 準備執行doInBackground任務時回調
protected void onPreExecute() {
super.onPreExecute();
}
@Override // doInBackground任務執行結束後回調,接收的參數爲doInBackground返回的值
protected void onPostExecute(Float aFloat) {
super.onPostExecute(aFloat);
}
@Override // doInBackground調用publishProgress會回調到該方法中
protected void onProgressUpdate(Double... values) {
super.onProgressUpdate(values);
}
@Override // 調用AsyncTask的任務關閉後回調
protected void onCancelled() {
super.onCancelled();
}
}
複製代碼
public AsyncTask(@Nullable Looper callbackLooper) {
// 建立AsyncTask對象時,若不傳外部的Handler實例,會走到這個構造中
// 拿到當前線程的Looper,傳給new的Handler,則Handler在當前建立AsyncTask對象的線程中
// 所以,若要保證Handler執行環境在主線程,必需要在主線程中建立AsyncTask對象
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
......省略無關代碼
}
複製代碼
MyTask myTask = new MyTask();
// 默認在SerialExecutor線程池中串行執行
myTask.execute("1");
// 並行執行
myTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "1");
複製代碼
@MainThread // 主線程中執行的方法,默認選擇SerialExecutor線程池串行執行任務
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
@MainThread // 主線程中執行的方法。外部也可直接調這個方法執行任務,本身傳入線程池選擇是串行仍是並行。
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
// 一個AsyncTask對象,若屢次執行execute,走到這裏,會判斷任務在執行中或已結束時,都將拋異常
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;
}
複製代碼