AsyncTask 工作原理分析

Stella981
• 阅读 531

AsyncTask 相信大家对他的使用并不陌生,它是谷歌官方提供的一种轻量级别的异步任务类,底层封装的是两个线程池和一个Handler.sDefaultExecutor=SERIAL_EXECUTOR 用来Runnable排队用的, THREAD_POOL_EXECUTOR 是用来真正执行任务的.

我们先从 execute()开始分析,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;
}

如果执行状态是Running(正在执行)或Finish(已经执行完了),抛出异常,所以一个AsyncTask 只能执行一次. 接着调用onPreExcute(),这就是为什么onPreEcxute是在执行实际的后台操作前被UI thread调用. 任务的真正执行是在exec.execute(mFuture) 中, exec 是 SerialExecutor 的一个对象,我们就去看看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);
        }
    }
}

我们可以知道AsyncTask在构造方法中把Params 参数转化为一个FutureTask,接着SerialExecutor 会把FutureTask对象插入到ArrayDeque 任务队列,ArrayDeque 内部使用数组存储数据,大小自增长的队列.从这里可以看书AsyncTask 是串行执行的,最终交给scheduleNext()去执行.

public AsyncTask() {
    mWorker = new WorkerRunnable<Params, Result>() {
        public Result call() throws Exception {
            mTaskInvoked.set(true);

            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            //noinspection unchecked
            Result result = doInBackground(mParams);
            Binder.flushPendingCommands();
            return postResult(result);
        }
    };

    mFuture = new FutureTask<Result>(mWorker) {
        [@Override](https://my.oschina.net/u/1162528)
        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);
            }
        }
    };
}

我们在public AsyncTask() {}构造方法中可以得知mWorker 首先将mTaskInvoked.set(true) 接着调用doInBackground(mParams) 返回Result,最后将其返回值传递给postResult(result).

private Result postResult(Result result) {
    @SuppressWarnings("unchecked")
    Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
            new AsyncTaskResult<Result>(this, result));
    message.sendToTarget();
    return result;
}

postResult ()获取一个InternalHandler ,通过InternalHandler 发送MESSAGE_POST_RESULT的消息,最终由InternalHandler 来处理消息

 private static class InternalHandler extends Handler {
    public InternalHandler() {
        super(Looper.getMainLooper());
    }

    @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
    [@Override](https://my.oschina.net/u/1162528)
    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 必须在主线中,所以AsyncTask必须在主线程中创建.

以上就是AsyncTask的工作原理分析. 通过以上分析我们可以得知:

    1. Task的实例必须在UI thread中创建
  1. execute方法必须在UI thread中调用

  2. 不要手动的调用onPreExecute(), onPostExecute(Result),doInBackground(Params...), onProgressUpdate(Progress...)这几个方法

  3. 该task只能被执行一次,否则多次调用时将会出现异常。 如果在子线程中创建调用 onPreExecute()也在创建AsyncTask的子线程中执行,doInBackground(Params...)在子线程中执行,onPostExecute(Result)和onProgressUpdate(Progress...)在主线程中

由于本人第一次写源码分析的文章,再加上本人表达能力有限,如若哪里有误,,还望多多拍砖,请与指正,谢谢

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Executor框架
任务是一组逻辑工作单元,而线程则是使任务异步执行的机制。线程池简化了线程的管理工作,并且java.util.concurrent提供了一种灵活的线程池实现作为Executor框架的一部分。在Java类库中,任务执行的主要抽象不是Thread,而是Executor,如下所示:publicinterfaceExecutor{void
Stella981 Stella981
2年前
Android 异步加载
一般会使用线程Thread、Timer或者使用AsyncTask,而这些操作都是在在后台另外开一个线程给我们找数据,具体得到的数据需要使用Handler去更新UI,AsyncTask也是一样使用到的Handler只是它将Handler封装在了onPostExecute执行操作中。使用过AsyncTask的同学都知道一个异步加载数据最少要
Stella981 Stella981
2年前
Python之time模块的时间戳、时间字符串格式化与转换
Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块。关于时间戳的几个概念时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量。时间元组(struct_time),包含9个元素。 time.struct_time(tm_y
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
为什么mysql不推荐使用雪花ID作为主键
作者:毛辰飞背景在mysql中设计表的时候,mysql官方推荐不要使用uuid或者不连续不重复的雪花id(long形且唯一),而是推荐连续自增的主键id,官方的推荐是auto_increment,那么为什么不建议采用uuid,使用uuid究
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这