AsyncTask 源码解析

一、前言
AsyncTask是一个异步任务。里面封装了线程池及Handler。所以,它可以方便地实现线程的切换及耗时任务的执行。
二、先上基本使用代码:

class CusAsyncTask extends AsyncTask<Long, Integer, Long>
    {
        // 第一个执行的方法,可在此做些初始化操作。工作在主线程MainThread
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        // 此处执行耗时操作。工作在工作线程WorkerThread
        @Override
        protected Long doInBackground(Long... values)
        {
            long startTime = System.currentTimeMillis();
            for (int progress = 0; progress < values[0]; progress ++)
            {
                // 此行代码会触发onProgressUpdate方法,实际使用中可用于进度更新
                publishProgress(progress);
            }
           // 此处return 的结果会当成参数传递到 onPostExecute 中
            return System.currentTimeMillis() - startTime;
        }

        // 进度更新操作,由publishProgress来触发。执行在主线程MainThread
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.e("onProgressUpdate ", values[0] + "");
        }

        // 参数result实际上是doInBackground返回的结果。执行在主线程MainThread。可把结果
           直接显示到相关控件上
        @Override
        protected void onPostExecute(Long result) {
            super.onPostExecute(result);
            Log.e("onPostExecute ", "耗时 : " + result+ "ms");
        }
    }

以下为调用方法:

CusAsyncTask cusAsyncTask = new CusAsyncTask();
        // 并行运行
        cusAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 100L);
        // 串行运行
//        cusAsyncTask.execute(100L);

三、流程及原理分析
1.先看看CusAsyncTask cusAsyncTask = new CusAsyncTask();都做了什么:

/**
     * Creates a new asynchronous task. This constructor must be invoked on the UI 
thread.
看到没有,初始化必须在UI线程也就是主线程中执行。
     */
    public AsyncTask() {
        this((Looper) null);
    }
    ......
/**
     * Creates a new asynchronous task. This constructor must be invoked on the UI
       thread.
     * 这是一个隐藏的函数。用于创建一个新的异步任务,由上面的构造函数所调用
     * @hide
     */
    public AsyncTask(@Nullable Looper callbackLooper) {
       // 这是必须要在主线程调用的原因,mHandler 需要主线程Handler
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    // 线程执行的时候,实际上就是执行call方法。此时doInBackground启动
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    // 最终onPostExecute方法被回调,一个任务流程结束
                    postResult(result);
                }
                return result;
            }
        };
        // 封装了Callable
        mFuture = new FutureTask<Result>(mWorker) {
            // 当 Callable 的 call() 方法执行完毕之后调用
            @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);
                }
            }
        };
    }

2.再看看cusAsyncTask.execute(100L)做了啥事。这样启动的任务是串行执行的

@MainThread
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
}

其中,sDefaultExecutor实际上是一个自定义的线程池。且该线程池一次只能按排队顺序地执行一个任务(串行)。当然这是高版本,低版本3.0之前默认是并行的。

private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
/**
 * 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线程池来执行任务
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
    }

回到正题executeOnExecutor

@MainThread
    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()最先执行的原因
        onPreExecute();

        mWorker.mParams = params;
        // 把任务排到任务队列队尾。此时,任务正式执行
        exec.execute(mFuture);

        return this;
    }

3.再看看并行启动的任务cusAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 100L);

/**
     * 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, sPoolWorkQueue, sThreadFactory);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

其中几个常量如下:

// CPU核数,“设置——>关于手机”那里可以看到是几核。一般有4,6,8...
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating
// the CPU with background work
// 核心线程数为2到4之间,这些线程通常会一直活着,不会销毁
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
// 最大线程数为:CPU核数 * 2 + 1。按目前的设备来看,一般在10-20左右
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
// 存活时间,即线程空闲时存活时间为30秒
private static final int KEEP_ALIVE_SECONDS = 30;
// 缓存任务数量最多128
private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 228,546评论 6 533
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,570评论 3 418
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 176,505评论 0 376
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,017评论 1 313
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,786评论 6 410
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,219评论 1 324
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,287评论 3 441
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,438评论 0 288
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,971评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,796评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,995评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,540评论 5 359
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,230评论 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,662评论 0 26
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,918评论 1 286
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,697评论 3 392
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,991评论 2 374

推荐阅读更多精彩内容