之前开发中经常使用AsyncTask进行异步数据获取,当时只限于使用,具体的代码细节没有仔细看过,今天就阅读一下源码,当作笔记。加深记忆
构造函数
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);
}
}
};
}
首先看WorkerRunnable,实现了Callable接口
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
再看一下首先看WorkerRunnable的初始化,由于是一个抽象类,需要实现内部方法,具体方法里面的实现是将mTaskInvoked设置为true,然后调用doInBackground方法,然后将doInBackground返回的结果集传参给postResult方法并返回。
我们看一下postResult方法到底是个什么
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
postResult方法内部创建了一条消息,message.what=MESSAGE_POST_RESULT,message.obj=new AsyncTaskResult<Result>(this, result),然后通过异步消息机制将消息传递出去。
那我们传递出去的obj又是个什么呢
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
一个很普通的类,就是将传入的参数保存一下
我们看一下处理消息的handler
private static Handler getHandler() {
synchronized (AsyncTask.class) {
if (sHandler == null) {
sHandler = new InternalHandler();
}
return sHandler;
}
}
private static class InternalHandler extends Handler {
public InternalHandler() {
super(Looper.getMainLooper());
}
@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;
}
}
}
看handleMessage方法,接收到之前的what参数MESSAGE_POST_RESULT,执行finish方法,我们看一下finish方法干了哪些事
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
逻辑很简单,判断任务是否取消,如果取消就执行onCancelled方法,如果没有取消就onPostExecute,最后将状态更改为结束状态
我们在次回到构造方法中,WorkerRunnable初始化完成之后开始进行FutureTask的任务初始化,将mWorker当做构造参数传入,覆写done方法
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中的任务执行完毕之后会执行postResultIfNotInvoked方法,我们接着再看一下这个方法发生了什么:
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
方法也比较简单,会去判断mTaskInvoked的true或false,mWorker执行完毕之后已经将mTaskInvoked设置了为true,所以if里面的语句一般是执行不到的
任务执行
到这异步任务的初始化分析已经完成了,接着异步任务初始化完成之后我们需要去执行他,也就是execute方法:
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
方法内部其实是调用了executeOnExecutor方法,我们再看一下这个方法:
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;
}
看核心部分exec.execute(mFuture),exec指向的是一个SerialExecutor实例
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);
}
}
}
在SerialExecutor内部维护了一个任务队列,通过offer方法将任务添加到队尾,任务执行完之后调用scheduleNext方法,scheduleNext方法内部将任务队列的队首任务取出,如果不为空的话就通过THREAD_POOL_EXECUTOR去执行这个任务
这个THREAD_POOL_EXECUTOR又是什么呢
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;
}
通过静态块去初始化了一个线程池,看一下线程池的参数
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE_SECONDS = 30;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
理想情况下核心线程数为4个,最大线程并发数是CPU数乘以2然后减1,最大支持4*2+1=9个的线程数,空闲线程存活时间为30S,然后还有一个长度128的线程队列,当我们有多个任务需要执行execute的时候,execute方法是一个同步方法,第一个任务入队,由poll取出执行,第二个任务需要等待第一个任务执行完毕之后才能执行,所以execute方法是任务串行。
在开发中大部分的情况是并行的,又要怎么样才能进行并行操作呢,我们可以直接使用executeOnExecutor方法执行任务,只需要指定一个线程池跟参数即可,我们可以用源码中提供的THREAD_POOL_EXECUTOR,这样就可以实现任务的并行。
网友评论