要查看一個(gè)類(lèi)實(shí)現(xiàn)的流程我注,我們需要先查看它類(lèi)說(shuō)明和成員變量。
AsyncTask說(shuō)明
/**
* <p>AsyncTask enables proper and easy use of the UI thread. This class allows to
* perform background operations and publish results on the UI thread without
* having to manipulate threads and/or handlers.</p>
*
* <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler}
* and does not constitute a generic threading framework. AsyncTasks should ideally be
* used for short operations (a few seconds at the most.) If you need to keep threads
* running for long periods of time, it is highly recommended you use the various APIs
* provided by the <code>java.util.concurrent</code> package such as {@link Executor},
* {@link ThreadPoolExecutor} and {@link FutureTask}.</p>
大概意思就是說(shuō)AsyncTask可以很容易并且正確地結(jié)合UI線程,它可以將任務(wù)運(yùn)行在后臺(tái)并且將結(jié)果返回給UI線程卓缰,這個(gè)過(guò)程不需要使用任何專(zhuān)門(mén)的操縱UI的線程或者Handler。其實(shí)AsyncTask就是對(duì)Thread和Handler的一個(gè)封裝掌挚。并且AsyncTask最好使用于需要很短執(zhí)行時(shí)間的任務(wù)雨席,非常耗時(shí)的任務(wù)應(yīng)該使用Executor或者ThreadPoolExecutor加 FutureTask.
AsyncTask的成員變量
//很明顯這是CPU的數(shù)量
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
//這是線程池初始化線程數(shù),為CPU數(shù)量加1
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
//這是線程池維護(hù)的最大的線程數(shù)吠式,CPU的兩倍加1
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
//當(dāng)線程數(shù)超過(guò)初始化的線程數(shù)時(shí)陡厘,多出來(lái)的空閑線程,存活的時(shí)間是1秒特占,除非在等待過(guò)程中會(huì)有任務(wù)到來(lái)
private static final int KEEP_ALIVE = 1;
//用于構(gòu)造線程池
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());
}
};
//線程池的任務(wù)隊(duì)列糙置,最大同時(shí)存在128個(gè)任務(wù)
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
//用來(lái)執(zhí)行任務(wù)的線程池,任務(wù)最終會(huì)交給它來(lái)處理
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
/**
* An {@link Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
//一個(gè)任務(wù)調(diào)度器是目,是串行性質(zhì)的谤饭。意思是只有上一個(gè)任務(wù)完成了,才會(huì)調(diào)度分發(fā)一個(gè)新的任務(wù)
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
//用于標(biāo)志信息的類(lèi)型懊纳,會(huì)在Message中使用
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
//默認(rèn)的執(zhí)行線程池
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
//用于返回結(jié)果或者傳遞進(jìn)度給UI線程
private static InternalHandler sHandler;
//任務(wù)包裝類(lèi)揉抵,實(shí)現(xiàn)的是Callable接口。負(fù)責(zé)將doInbackground的任務(wù)包裝
private final WorkerRunnable<Params, Result> mWorker;
//將WorkerRunnable進(jìn)一步包裝并且處理返回結(jié)果嗤疯,實(shí)現(xiàn)的是RunnableFuture接口
private final FutureTask<Result> mFuture;
接下來(lái)我們看AsyncTask的入口execute(...)方法
@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
可以看到它是運(yùn)行在主線程的方法冤今,它調(diào)用的是executeOnExecutor(...),我們接著進(jìn)入該方法茂缚。
@MainThread
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;
}
可以看到先調(diào)用的是onPreExecute()方法戏罢,這個(gè)方法也是在主線程執(zhí)行的屋谭。然后就執(zhí)行Executor的execute()方法,這里傳進(jìn)去的是一個(gè)mFuture龟糕,前面我們知道它是一個(gè)RunnableFuture接口的實(shí)現(xiàn)類(lèi)桐磁,它是在哪初始化的呢?答案是在AsyncTask的構(gòu)造函數(shù)中
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
Result result = doInBackground(mParams);
Binder.flushPendingCommands();
return postResult(result);
}
};
mFuture = new FutureTask<Result>(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 occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
初始化了mWorker翩蘸,并且在call()方法中調(diào)用了doInBackground方法所意,并且調(diào)用了postResult方法。postResult其實(shí)就是返回結(jié)果給UI線程催首。
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
我們來(lái)進(jìn)去FutureTask里面扶踊,可以看到run方法
public void run() {
if (state != NEW ||
!U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
return;
try {
Callable<V> 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);
}
}
可以看到里面執(zhí)行了callable的call()方法,然后設(shè)置了返回結(jié)果郎任。在mFuture里面秧耗,done方法依然會(huì)做一個(gè)判斷,判斷該結(jié)果是否已經(jīng)返回過(guò)了舶治,如果沒(méi)有返回則提交返回分井。
說(shuō)了這么多我們竟然沒(méi)看到ThreadPoolExecutor的使用,好吧忘記說(shuō)了霉猛。
在說(shuō)明execute方法時(shí)尺锚,我們說(shuō)到了exec.execute(...),這個(gè)exec其實(shí)就是SerialExecutor對(duì)象惜浅,我們進(jìn)去看個(gè)究竟
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);
}
}
}
可以看到里面設(shè)置了一個(gè)雙端隊(duì)列瘫辩,來(lái)存儲(chǔ)任務(wù)。在SerialExecutor的execute方法中坛悉,先是把FutureTask插入到了雙端隊(duì)列伐厌,然后判斷這時(shí)候有沒(méi)有任務(wù)正在執(zhí)行,如果沒(méi)有則通過(guò)scheduleNext()方法調(diào)度下一個(gè)任務(wù)給線程池THREAD_POOL_EXECUTOR去執(zhí)行.
我們來(lái)總結(jié)一下大概的流程:AsyncTask執(zhí)行execute方法裸影,首先調(diào)用的是onPreExecute方法挣轨,然后將執(zhí)行參數(shù)傳遞給WorkerRunnable(是一個(gè)Callable的實(shí)現(xiàn)類(lèi)),WorkerRunnable中call方法調(diào)用的是doInBackground方法轩猩,并處理了返回結(jié)果卷扮。然后FutureTask進(jìn)一步封裝了WorkerRunnable對(duì)象,然后將Future交給SerialExecutor去調(diào)度界轩。SerialExecutor會(huì)把任務(wù)交給線程池去執(zhí)行画饥,線程池執(zhí)行FutureTask的run方法,該方法其實(shí)就是取得WorkerRunnable的call方法浊猾。處理完成后檢查結(jié)果是否已經(jīng)在call方法中返回了抖甘,如果沒(méi)有則提交返回。
其實(shí)在3.0之前葫慎,任務(wù)默認(rèn)是并發(fā)執(zhí)行的衔彻。3.0之后串行執(zhí)行薇宠,如果仍需要并發(fā)執(zhí)行則可以通過(guò)executeOnExecutor方法來(lái)執(zhí)行,而不是execute(...)方法艰额。其實(shí)executeOnExecutor方法本質(zhì)上就是繞過(guò)了SerialExecutor的調(diào)度澄港,直接將任務(wù)提交給線程池。
以前的版本
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 10;
private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(10);
與以前相比柄沮,默認(rèn)的線程池大小變了回梧,現(xiàn)在是CPU數(shù)量+1
任務(wù)隊(duì)列也變了。由10變成128
最大線程數(shù)原來(lái)是128祖搓,現(xiàn)在是2*CPU數(shù)+1
以前是并發(fā)執(zhí)行狱意,現(xiàn)在是串行執(zhí)行。