用途
AsyncTask翻译成中文就是异步任务,这个类可以让我们在不使用多线程或Handler的情况下在后台进行操作并将结果发送到UI线程。
实现方式
AysncTask是通过Handler+Thread来实现,它作为一个工具类,不能当成线程框架来使用。
注意事项
AsyncTask理想状态下是用于较短的耗时操作,如果希望线程长时间运行,建议使用Executor, ThreadPoolExecutor和FutureTask
源码分析
1.创建线程池
AsyncTask会创建两个Executor,一个串行,一个并行
串行Executor
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);
}
}
}
并行Executor
/**
* An {@link Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR;
static {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), sThreadFactory);
threadPoolExecutor.setRejectedExecutionHandler(sRunOnSerialPolicy);
THREAD_POOL_EXECUTOR = threadPoolExecutor;
}
AsyncTask默认为串行Executor
2.执行方式
//执行AsyncTask,使用默认的串行Executor
task.execute(null)
//执行AsyncTask,使用指定的Executor,可以自定义Executor来指定
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null)
网友评论