AsyncTask詳解
掃描二維碼
隨時隨地手機看文章
? ? ? ? 作為Android中最常用跨線程手段之一,AsyncTask經(jīng)常出現(xiàn)在代碼中。我也經(jīng)常使用AsyncTask,有一次遇到一個奇怪的情況:AsyncTask.execute()函數(shù)調用后,AsyncTask卻未立即執(zhí)行,而是過了一段時間以后,才開始執(zhí)行,當時覺得很奇怪,一番Google后,得知是線程池的原因。事后也一直擱著,直到今天工作有點空,花了點時間看看AsyncTask的實現(xiàn)。
AsyncTask的線程池??????? AsyncTask提供了兩個線程池,用以執(zhí)行后臺任務:
??????? 當然,開發(fā)者也可以通過自定義線程池來執(zhí)行后臺任務:
??????? THREAD_POOL_EXECUTOR的定義為:
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
??????? 其中用到的一些參數(shù)如下:
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 ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());//創(chuàng)建一個擁有特定名字的線程
}
};
private static final BlockingQueue sPoolWorkQueue =
new LinkedBlockingQueue(10);
??????? 這里不詳細解釋ThreadPoolExecutor的實現(xiàn),而是簡單介紹下ThreadPoolExecutor的工作邏輯(線程池的工作邏輯,相信大家都比較清楚)
當線程池內無空閑線程,且線程數(shù)不足CORE_POOL_SIZE時,創(chuàng)建新的線程來執(zhí)行任務。當線程池內無空閑線程,且線程數(shù)大于等于CORE_POOL_SIZE,且sPoolWorkQueue為滿時,把任務放到sPoolWorkQueue中。當線程池內無空閑線程,且線程數(shù)大于等于CORE_POOL_SZIE,且sPoolWorkQueue已滿,且線程數(shù)未達到MAXIMUM_POOL_SIZE時,創(chuàng)建新線程以執(zhí)行任務。當線程池內無空閑線程,且線程數(shù)大于等于CORE_POOL_SZIE,且sPoolWorkQueue已滿,且線程數(shù)等于MAXIMUM_POOL_SIZE時,拋出異常。?????? 從當前的參數(shù)我們可以看到,THREAD_POOL_EXECUTOR最多同時擁有128個線程執(zhí)行任務,通常情況下(sPoolWorkQueue有任務,且未滿),THREAD_POOL_EXECUTOR會擁有5條線程同時處理任務。
??????? 默認情況下,AsyncTask會在SERIAL_EXECUTOR中執(zhí)行后臺任務(其實,這個說法不太準確,稍后解釋):
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
??????? SERIAL_EXECUTOR的定義為:
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
??????? 而SerialExecutor的定義為: private static class SerialExecutor implements Executor {
final ArrayDeque mTasks = new ArrayDeque();
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);
}
}
}
??????? 從這里,我們可以看到SerialExecutor并不是一個線程池(所以本文前面說AsyncTask的兩個線程池的說法是不準確的),它實際上是提供了一個mTask來儲存所有待執(zhí)行的task,并逐個提交給THREAD_POOL_EXECUTOR執(zhí)行。?????? 所以,實際上所有的后臺任務都是在THREAD_POOL_EXECUTOR中執(zhí)行的,而
AsyncTask.execute()
??????? 和AsyncTask.executorOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
??????? 的差別在于,前者會逐個執(zhí)行任務,同一時間僅有一個任務被執(zhí)行。AsyncTask的實現(xiàn)
??????? AsyncTask的實現(xiàn),需要依賴于兩個成員:
private final WorkerRunnable mWorker;
private final FutureTask mFuture;
WorkerRunnable
??????? WorkerRunnable的定義為:
private static abstract class WorkerRunnable implements Callable {
Params[] mParams;
}
??????? 而Callable的定義為:
public interface Callable {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
???????? WorkerRunnable為抽象類,所以使用的其實是它的子類:
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask(mWorker) {
@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 occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
???????? call函數(shù)的重載挺簡單,主要就是調用doInBackground函數(shù),執(zhí)行后臺任務。
??????? FutureTask的實現(xiàn)比WorkerRunnable復雜,但是,如果抓住核心去分析也很簡單。
??????? 首先, FutureTask實現(xiàn)了RunnableFuture接口:
public class FutureTask implements RunnableFuture {
??????? 然后,RunnableFuture繼承自Runnable:public interface RunnableFuture extends Runnable, Future {
/**
* Sets this Future to the result of its computation
* unless it has been cancelled.
*/
void run();
}
??????? 所以,F(xiàn)utureTask類,肯定實現(xiàn)了run方法: public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.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);
}
}
??????? 忽略其他處理,run函數(shù)執(zhí)行了callable的call函數(shù)。再說說callable是什么東西: public FutureTask(Callable callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
????? 在看看前面已經(jīng)介紹過的AsyncTask構造函數(shù): /**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask(mWorker) {
@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 occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
?????? 原來callable就是mWorker,也就是說,F(xiàn)utureTask的run函數(shù),會調用doInBackground函數(shù)。AsyncTask.execute函數(shù)的執(zhí)行過程 ?????? 1. AsyncTask.execute
public final AsyncTask execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
?????? 2.AsyncTask.executeOnExecutor public final AsyncTask 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();//調用onPreExecute
mWorker.mParams = params;//保存參數(shù)
exec.execute(mFuture);//執(zhí)行task
return this;
}
??????? 跳過SERIAL_EXECUTOR和THREAD_POOL_EXECUTOR的實現(xiàn)不談,我們可以用如下的方式,簡單理解exe.execute函數(shù):void execute(Runnable runnable){
new Thread(runnable).start();
}
??????? 3. FutureTask.run() public void run() {
if (state != NEW ||
!UNSAFE.compareAndSwapObject(this, runnerOffset,
null, Thread.currentThread()))
return;
try {
Callable c = callable;
if (c != null && state == NEW) {
V result;
boolean ran;
try {
result = c.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);
}
}
???????? 前面已經(jīng)講過,會調用mWorker.call().???????? 4. WorkerRunnable.call()
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
????????? 5. AsyncTask.postResult() private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
???????? 通過sHandler,去UI線程執(zhí)行接下來的工作。??????? 6. sHandler.handleMessage
private static class InternalHandler extends Handler {
@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;
}
}
}
??????? 7. AsyncTask.finish private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
??????? 通常情況下(即尚未調用過cancel(boolean interrupt)),isCannelled()為false,接下來會執(zhí)行onPostExecute。總結
?????? 從本質上來講,AsyncTask即為Execute和Handler的組合。AsyncTask利用Executor在后臺線程中執(zhí)行doInBackgroud函數(shù),并利用handler執(zhí)行onPostExecute函數(shù)。
?????? 而AsyncTask的行為則由executeOnExecutor函數(shù)中參數(shù)exec決定。AsyncTask提供的SERIAL_EXECUTOR限定任務逐個執(zhí)行,而THREAD_POOL_EXECUTOR支持最多128個任務并行執(zhí)行,但是當待處理任務過多時,會拋出RejectedExecutionException。