Asynctask踩坑

2017-10-31  本文已影响19人  爱码士平头哥

AsyncTask作为一个优秀的封装,很多人都在用,可是我估计很多人并不清楚多个AsyncTask对象到底是串行执行的,还是并行执行的,如果是并行的,那么最多同时执行几个异步任务呢?

源码面前无秘密,我们看一下源代码就知道了。

这里以Android-23为例。

AyncTask调用例子

[html]view plaincopy

AsyncTasktask=newAsyncTask() {

@Override

protected Object doInBackground(Object[] params) {

return null;

}

};

task.execute();

普通AsyncTask对象调用如上,主要是通过task.execute()来执行异步任务。那么execute到底做了什么呢?

AsyncTask的execute函数

看看实现:

[html]view plaincopy

@MainThread

public final AsyncTaskexecute(Params... params) {

return executeOnExecutor(sDefaultExecutor, params);

}

超简单,就一行。先看看executeOnExecutor函数:

[html]view plaincopy

@MainThread

public final AsyncTaskexecuteOnExecutor(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是什么呢?从execute函数里面的实现就可以看到,exec是sDefaultExecutor,那么sDefaultExecutor是什么玩意呢?

从一下代码可以清楚的看到:

[html]view plaincopy

public static final ExecutorSERIAL_EXECUTOR=newSerialExecutor();

private static final intMESSAGE_POST_RESULT=0x1;

private static final intMESSAGE_POST_PROGRESS=0x2;

private static volatile ExecutorsDefaultExecutor=SERIAL_EXECUTOR;

sDefaultExecutor是SerialExecutor的一个实例,而且它是个静态变量。也就是说,一个进程里面所有AsyncTask对象都共享同一个SerialExecutor对象。

那么所有的秘密就在于SerialExecutor的execute函数了。

SerialExecutor的execute函数

直接贴出SerialExecutor的实现:

[html]view plaincopy

private static class SerialExecutor implements Executor {

final ArrayDequemTasks=newArrayDeque();

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);

}

}

}

代码本身很简单,从execute里面就能看出,异步任务r被放到了ArrayDeque对象mTasks中,然后通过scheduleNext()来从mTasks里面得到一个任务去一个后台线程执行。

在一个异步任务执行后,再次调用scheduleNext来执行下一个任务(run函数)。

所以,很清楚,其实SerialExecutor是一个一个执行任务的,而所有的AsyncTask对象又共享同一个SerialExecutor对象(静态成员)。

所以,我们可以肯定:至少在Android-23 SDK里面,多个AsyncTask对象是串行执行的。

实际是不是呢,做个实验就知道:

测试代码超简单,就是创建3个AsyncTask对象,做了一样的事情,就是在doInBackground里面打印log。

我们从log可以清楚的看到,AsyncTask对象1,2,3是串行执行的。

这也证实了,Android-23 sdk里面 多个AsyncTask对象确实是串行执行的。

如何并行执行多个AsyncTask对象

那么有没有办法并行执行呢?肯定有了。

看AsyncTask的实现,里面有个Executor

[html]view plaincopy

public static final ExecutorTHREAD_POOL_EXECUTOR

=newThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,

TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

如果我们直接使用THREAD_POOL_EXECUTOR会怎么样呢?

看下图:

这次的执行顺序跟上次不一样了。可以看出好像3个任务并行执行了。不像之前的排队执行。

关于THREAD_POOL_EXECUTOR,有兴趣可以看进去,大致的意思就是,

[html]view plaincopy

private static final intCPU_COUNT=Runtime.getRuntime().availableProcessors();

private static final intCORE_POOL_SIZE=CPU_COUNT+ 1;

private static final intMAXIMUM_POOL_SIZE=CPU_COUNT* 2 + 1;

这是个线程池,有两个概念,一个是线程池里面核心线程数,一个是最大线程数。从上面的定义可以大概看出来,核心线程数是CPU个数+1,最大是CPU个数 * 2 + 1.

至于怎么调度执行,那就有一套算法了,这里就不介绍了。但是有一点可以肯定,它不是排队在一个线程里面执行的,所以也就看到了上面的结果。

实际上,我们也可以自己实现 一个执行器,如:

[html]view plaincopy

public class MyThreadPoolExecutor extends AbstractExecutorService

然后调用AsyncTask的executeOnExecutor,把自己的MyThreadPoolExecutor对象传进去,达到自己想要的效果。

不过,还是推荐使用系统默认的,也就是排队执行的方式,除非有特殊需求,我们才搞特殊化处理。

原文地址:http://blog.csdn.net/zj510/article/details/51622597

上一篇下一篇

猜你喜欢

热点阅读