[转]【安卓笔记】AsyncTask源码剖析
[转]【安卓笔记】AsyncTask源码剖析
http://blog.csdn.net/chdjj/article/details/39122547
前言:
- public abstract class AsyncTask<Params, Progress, Result>
- public static final Executor THREAD_POOL_EXECUTOR
- = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
- TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
ThreadPoolExecutor
各参数含义如下,CORE_POOL_SIZE为核心线程数量,MAXIMUM_POOL_SIZE为线程池最大线程数量,KEEP_ALIVE参数表明
当线程池的线程数量大于核心线程数量,那么空闲时间超过KEEP_ALIVE时,超出部分的线程将被回收,sPoolWorkQueue是任务队列,存储
的是一个个Runnable,sThreadFactory是线程工厂,用于创建线程池中的线程。所有这些参数在AsyncTask内部都已经定义好:
- private static final int CORE_POOL_SIZE = 5;
- private static final int MAXIMUM_POOL_SIZE = 128;
- private static final int KEEP_ALIVE = 1;
- 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());
- }
- };
- private static final BlockingQueue<Runnable> sPoolWorkQueue =
- new LinkedBlockingQueue<Runnable>(10);
AsyncTask并不是直接使用上述线程池,而是进行了一层“包装”,这个类就是SerialExecutor,这是个串行的线程池。
- /**
- * An {@link Executor} that executes tasks one at a time in serial
- * order. This serialization is global to a particular process.
- */
- public static final Executor SERIAL_EXECUTOR = new 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);
- }
- }
- }
空,第一次调用,此值为空,所以会调用scheduleNext方法,从队列中取出头部的任务,交给线程池THREAD_POOL_EXECUTOR处
理,而处理过程是这样的,先执行原先的Runnable的run方法,接着再执行scheduleNext从队列中取出Runnable,如此循环,直到
队列为空,mActive重新为空为止。我们发现,经过这样的处理,所有任务将串行执行。
- private static final int MESSAGE_POST_RESULT = 0x1;//当前消息类型--->任务完成消息
- private static final int MESSAGE_POST_PROGRESS = 0x2;//当前消息类型-->进度消息
- private static final InternalHandler sHandler = new InternalHandler();
- private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;//默认线程池
- private final WorkerRunnable<Params, Result> mWorker;
- private final FutureTask<Result> mFuture;
- private volatile Status mStatus = Status.PENDING;//当前状态
- private final AtomicBoolean mCancelled = new AtomicBoolean();
- private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
sDefaultExecutor指明默认的线程池是串行池,mStatus指明当前任务状态,Status是个枚举类型:
- public enum Status {
- /**
- * Indicates that the task has not been executed yet.
- */
- PENDING,//等待执行
- /**
- * Indicates that the task is running.
- */
- RUNNING,//执行
- /**
- * Indicates that {@link AsyncTask#onPostExecute} has finished.
- */
- FINISHED,//执行结束
- }
重点看InternalHandler实现:
- private static class InternalHandler extends Handler {
- @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;
- }
- }
- }
InternalHandler继承自Handler,并复写了handleMessage,该方法根据消息类型做不同处理,如
果任务完成,则调用finish方法,而finish方法根据任务状态(取消or完成)调用onCancelled或者onPostExecute,这两
个是回调方法,通常我们会在onPostExecute中根据任务执行结果更新UI,这也是为什么文档中要求AsyncTask必须在UI线程中创建的原
因,我们的Handler须与UI线程的Looper绑定才能更新UI,并且子线程默认是没有Looper的。
- private void finish(Result result) {
- if (isCancelled()) {
- onCancelled(result);
- } else {
- onPostExecute(result);
- }
- mStatus = Status.FINISHED;
- }
- public final AsyncTask<Params, Progress, Result> execute(Params... params) {
- return executeOnExecutor(sDefaultExecutor, params);
- }
并没有直接调用doInbackground,而是调用了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;
- }
FutureTask类型,FutureTask是Runnable的实现类(j.u.c中的),所以可以作为线程池execute方法的参数,我们找到
其定义:
- 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 occured while executing doInBackground()",
- e.getCause());
- } catch (CancellationException e) {
- postResultIfNotInvoked(null);
- }
- }
- };
我们都知道,FutureTask构造时必须传入一个Callable的实现类,线程最终执行的是Callable的call方法(不明白的请看java线程并发库),所以mWorker必然是Callable的实现类:
- private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
- Params[] mParams;
- }
- Worker = new WorkerRunnable<Params, Result>() {
- public Result call() throws Exception {
- mTaskInvoked.set(true);
- Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
- //noinspection unchecked
- return postResult(doInBackground(mParams));
- }
- };
- private Result postResult(Result result) {
- @SuppressWarnings("unchecked")
- Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
- new AsyncTaskResult<Result>(this, result));
- message.sendToTarget();
- return result;
- }
这个AsyncTaskResult封装了数据域和对象本身:
- private static class AsyncTaskResult<Data> {
- final AsyncTask mTask;
- final Data[] mData;
- AsyncTaskResult(AsyncTask task, Data... data) {
- mTask = task;
- mData = data;
- }
- }
2.任务进度更新消息是通过publishProgress方法发送的:
- protected final void publishProgress(Progress... values) {
- if (!isCancelled()) {
- sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
- new AsyncTaskResult<Progress>(this, values)).sendToTarget();
- }
- }
[转]【安卓笔记】AsyncTask源码剖析的更多相关文章
- [笔记]LibSVM源码剖析(java版)
之前学习了SVM的原理(见http://www.cnblogs.com/bentuwuying/p/6444249.html),以及SMO算法的理论基础(见http://www.cnblogs.com ...
- STL源码剖析读书笔记之vector
STL源码剖析读书笔记之vector 1.vector概述 vector是一种序列式容器,我的理解是vector就像数组.但是数组有一个很大的问题就是当我们分配 一个一定大小的数组的时候,起初也许我们 ...
- AsyncTask源码笔记
AsyncTask源码笔记 AsyncTask在注释中建议只用来做短时间的异步操作,也就是只有几秒的操作:如果是长时间的操作,建议还是使用java.util.concurrent包中的工具类,例如Ex ...
- 【安卓网络请求开源框架Volley源码解析系列】定制自己的Request请求及Volley框架源码剖析
通过前面的学习我们已经掌握了Volley的基本用法,没看过的建议大家先去阅读我的博文[安卓网络请求开源框架Volley源码解析系列]初识Volley及其基本用法.如StringRequest用来请求一 ...
- c++ stl源码剖析学习笔记(一)uninitialized_copy()函数
template <class InputIterator, class ForwardIterator>inline ForwardIterator uninitialized_copy ...
- Hadoop源码学习笔记之NameNode启动场景流程二:http server启动源码剖析
NameNodeHttpServer启动源码剖析,这一部分主要按以下步骤进行: 一.源码调用分析 二.伪代码调用流程梳理 三.http server服务流程图解 第一步,源码调用分析 前一篇文章已经锁 ...
- 《STL源码剖析》读书笔记
转载:https://www.cnblogs.com/xiaoyi115/p/3721922.html 直接逼入正题. Standard Template Library简称STL.STL可分为容器( ...
- 通读《STL源码剖析》之后的一点读书笔记
直接逼入正题. Standard Template Library简称STL.STL可分为容器(containers).迭代器(iterators).空间配置器(allocator).配接器(adap ...
- ffmpeg/ffplay源码剖析笔记<转>
转载:http://www.cnblogs.com/azraelly/ http://www.cnblogs.com/azraelly/archive/2013/01/18/2865858.html ...
随机推荐
- Linux Centos下编译安装Redis
需要安装 tcl 8.5 wget http://downloads.sourceforge.net/tcl/tcl8.6.1-src.tar.gz //直接下载 sudo tar xzvf tcl8 ...
- LeetCode第七天
==数组 Medium== 40.(162)Find Peak Element JAVA //斜率思想,二分法 class Solution { public int findPeakElement( ...
- pep 8 规范的一些记录
一.pep8起源 龟叔创立Python的初衷里就有创立一个容易阅读的编程语言,所以亲自操刀写了pep8 代码规范,每个项目开始前都要有一个共识,就是自己的代码规范,pep8 就是一个很好的范本. 二. ...
- sonar + jacoco + mockMvc 模拟session 用户登录 配合SpringSecurity 权限 快速测试代码覆盖率.
遇到mock 测试简直就是神器,特别是要做代码覆盖率,直接测试controller就好了,缺点,虽然可以回滚事务,但是依赖数据库数据,解决,根据SpringBoot ,再建立一个专门跑单元测试的数据库 ...
- spring boot actuator 简单使用
spring boot admin + spring boot actuator + erueka 微服务监控 简单的spring boot actuator 使用 POM <dependenc ...
- JVM笔记1-内存溢出分析问题与解决
假设我们项目中JVM内存溢出了,大项目中上百万行代码,是很难定位的.因此我们需要借用一个Memory Analyzer工具, 官网地址为:http://www.eclipse.org/download ...
- 利用Apache配置本地 自定义域名
第一步:配置 httpd.conf 开启 虚拟主机 配置模块 去掉 " Include conf/extra/httpd-vhosts.conf " 前面的" # &qu ...
- 使用tcpcopy导入线上流量进行功能和压力测试
- 假设我们要上线一个两年内不会宕机的先进架构.在上线前,免不了单元测试,功能测试,还有使用ab,webbench等等进行压力测试. 但这些步骤非生产环境下正式用户的行为.或许你会想到灰度上线,但毕竟 ...
- CSRF的本质及防御
本质:产生的原因本质上是参数可知或可预测 防御: 1.加密参数:加密加盐,不可知,不可预测 忧虑,引入其他麻烦:一.数据分析困难 ...
- 编译、裁剪、安装、删除 Ubuntu内核和模块管理
一.下载最新内核文件 地址:http://www.kernel.org,一般下载Full Source版本. 下载完毕后,放到任意文件夹中,使用命令: tar jxvf linux-x.x.x.tar ...