[转]【安卓笔记】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 ...
随机推荐
- php的ob函数实现页面静态化
首先介绍一下php中ob缓存常用到的几个常用函数ob_start():开启缓存机制ob_get_contents():获取ob缓存中的内容ob_clean()清除ob缓存中的内容,但不关闭缓存ob_e ...
- Java8的一些新特性
速度更快: 代码更少(增加了新的语法Lamdba表达式): Lamdba操作符"->" 语法格式: 左侧:参数列表 右侧:接口抽象方法的实现功能 Lamdba表达式 3.强大 ...
- Mac下VirtualBox共享文件夹设置
环境:CentOS7.2最小化安装 步骤: 先安装必要软件包 yum install -y gcc gcc-devel gcc-c++ gcc-c++-devel make kernel kernel ...
- ios开发之自定义textView
自定义textView,从理论上讲很简单,根据需求自定义,比如我在开发中的需求就是现实一个字数的限制以及根据输入的文字改变提示剩余字数,那么开始我的基本思路就是自定义一个View,而里面包含一个子控件 ...
- linux HAProxy及Keepalived热备
HAProxy 它是免费,快速且可靠的一种解决方案没,适用于那些负载特大的web站点这些站点通常又需要会话保持或七层处理提供高可用性,负载均衡及基于tcp和http应用的代理 衡量负载均衡器性能的因素 ...
- Jenkins构建Android项目持续集成之findbugs的使用
Findbugs简介 关于findbugs的介绍,可以自行百度下,这里贴下百度百科的介绍.findbugs是一个静态分析工具,它检查类或者 JAR 文件,将字节码与一组缺陷模式进行对比以发现可能的问题 ...
- Android RocooFix热修复动态加载框架介绍
RocooFix Another hotfix framework 之前的HotFix项目太过简单,也有很多同学用Nuwa遇到很多问题,作者也不再修复,所以重新构建了一套工具. Bugfix 2016 ...
- 嵌入式 视频编码(H264)
这几天在编写视频录制模块,所以,闲暇之余,又粗粗的整理了一下,主要是API,以备不时之用 摄像头获取的模拟信号通过经芯片处理(我们使用的是CX25825),将模拟信号转成数字信号,产生标准的IT ...
- 【html5】html学习笔记1
html5语法规则 1.标签要小写 2.省略标签 如 <tr> <td> <tr><td> 3.属性不加” 如 <div id=div1> ...
- zTree实现更新根节点中第i个节点的名称
zTree实现更新根节点中第i个节点的名称 1.实现源码 <!DOCTYPE html> <html> <head> <title>zTree实现基本树 ...