AsyncTask 大家都熟悉吧,虽说以前我写过分析 AsyncTask 实现的文章,但是这里咱们从线程的角度来看 AsyncTask,探寻 AsyncTask 中的线程池应用,原来的文章我就不动了
AsyncTask 定义:
private class MyTask extends AsyncTask {
@Override
protected void onPreExecute() {... }
@Override
protected Long doInBackground(String... params) {... }
@Override
protected void onProgressUpdate(Object... values) {... }
@Override
protected void onPostExecute(Long aLong) {... }
@Override
protected void onCancelled() {... }
AsyncTask 中有2个线程池:
既然是探寻线程池的应用,按我们先来看线程池好了,AsyncTask 声明了2个线程池,但是有一个线程池非彼线程池,我们来看看她们的定义就清楚了
// 这是个普通的线程池
public static final Executor THREAD_POOL_EXECUTOR;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
sPoolWorkQueue, sThreadFactory);
threadPoolExecutor.allowCoreThreadTimeOut(true);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
---------------------------------------------------------------------------
// 这是个套着线程池皮的队列
public static final Executor SERIAL_EXECUTOR = new 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 默认使用的就是 SerialExecutor 这个线程池提交任务。SerialExecutor 提交任务是往自己的队列里添加了一个 Runnable 方法,然后激活另外的那个常规线程池从自己的队列里获取任务执行,但是 SerialExecutor 添加的这个 Runnable 在执行完 run 方法之后也会激活常规线程池从队列里获取任务执行,这样就形成了循环,和 ThreadPoolExecutor 里面的 Worker 循环获取阻塞队列里的任务有异曲同工之妙,核心都是转起来轮询获取队列任务,区别是怎么转起来,相当同的是他们都选择了 run 方法里做实现
AsyncTask 如何实现切换线程
核心就是使用了 Handler 机制,任务计算完成使用 Handler 发送消息。在 AsyncTask 的构造方法里搞了一个 WorkerRunnable,实际就是 Callable,然后配合 FutureTask 添加进线程池执行任务,WorkerRunnable 里面在 doInBackground(mParams) 异步计算完之后,通过 postResult(result) 用 handle 实现切换线程
public AsyncTask(@Nullable Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
mWorker = new WorkerRunnable() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
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 occurred while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
handle 抛出任务,obj 传入的就是 AsyncTask 对象本身
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler(): new Handler(callbackLooper);
private static Handler getMainHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler(Looper.getMainLooper());
}
return sHandler;
}
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult(this, result));
message.sendToTarget();
return result;
}
InternalHandler 在主线程相应消息,执行回调
private static class InternalHandler extends Handler {
public InternalHandler(Looper looper) {
super(looper);
}
@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;
}
}
}
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
ok 就这么点,AsyncTask 看起来很简单不是,为啥,因为我们之前已经深入充分的学习过了多线程,线程池的基本知识,也有过很多自己的思考,在夯实基础之后,我们再来看相关的应用就感觉简单多了,好理解了,但是大家要是不熟悉多线程,线程池的知识点,那看起来就是天书,编码就是这样,相关基础知识点直观重要