AsyncTask 源码分析

本文详细解析了Android中AsyncTask的源码实现,包括构造函数、执行任务等关键环节,并探讨了线程间通信机制及任务执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AsyncTask源码解析

一、先来看一个例子:使用异步任务类实现(1,100)的求和。

private class TestAsyncTask extends AsyncTask<Integer,Integer,Integer>{

        private int sum = 0;
        private int i = 0;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Integer doInBackground(Integer... integers) {

            while(i < 100){
                sum += i;
                i ++;
            }


            return sum;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            System.out.println("337----------------:sum(1,100) is:"+integer);
        }
    }

}

使用如下:


 mTestTask = new TestAsyncTask();
 mTestTask.execute();

从使用方面来讲,代码很精减,创建实例对象,再调用执行方法即可。
在使用的过程中,可以发现2个有意思的现象:

  • 可以在下述接口函数中更新UI

    • onProgressUpdate(Integer… values)
    • onPostExecute(Integer integer)
  • mTestTask实例只能启动一次,第二次启动的时候就会报异常

我们将带着这2个问题来分析下 AsyncTask内部实现原理。

二、构造函数的结构

  • 构造函数二 :源码上将英文内容为:创建一个异步任务,当前构造器必须在UI线程中调用
 /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        this((Looper) null);
    }

在这个构造器内部,又调用一个构造器,即最终构造实例并非由此构造,真正构造的是由

this((Loop) null)

在键盘上使用command +b发现它定位到了构造器二

  • 构造函数二 :内容如下
/**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     *
     * @hide
     */
    public AsyncTask(@Nullable Looper callbackLooper) {
        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
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    postResult(result);
                }
                return result;
            }
        };

        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 occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

这个构造器,干了3件事
- 创建Handler对象 :用来实现子线与主线程进行通信的,那么我文章前我们提的问题就得到了线索,等下再具体分析它在AsyncTask如何实现线程通信的

  • 创建WorkerRunnable: 处理工作任务实体,因为在它这里我们发现了一个doInBackground(mParams); 处理耗时任务的方法,所以断定它是用来处理耗时任务的,除此之外在创建这个实例对象中,发现如下代码:
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
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    postResult(result);
                }
                return result;
            }
        };

doInBackground接口返回的数据类型与我们定义使用这个异步任务类的时候一致,并在finally里调用了 postResult(result) 即将结果添加到了Handler中的mesage队列中,


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

假设再找到一个在主线程处理这个message队列中的消息,是不是就能实现线程间的通信了呢,答案是肯定的,我们只要证明这个假设存在即可。

回到前面创建那个Handler代码处,看看它是如何创建这个Handler实例的:

mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

getMainHandler源码为:

    private static Handler getMainHandler() {
        synchronized (AsyncTask.class) {
            if (sHandler == null) {
                sHandler = new InternalHandler(Looper.getMainLooper());
            }
            return sHandler;
        }
    }

InternalHandler 源码为:

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

        @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;
            }
        }
    }

终于找到了handleMessage接口,finish接口代码如下:

    private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }

找到了onPostExecute与onProgressUpdate接口,所以它能够在这2个接口里进行ui更换操作

  • 创建FutureTask: 创建任务类,并将任务实体类当作参数传给了构造器,可以理解为是对WorkerRunnable,因为在后面的分析可以看到 真正执行run方法对象是WorkerRunnable

三、执行任务

执行任务的调用代码如下:

mTestTask.execute();

execute()源码如下:

/**
     * Convenience version of {@link #execute(Object...)} for use with
     * a simple Runnable object. See {@link #execute(Object[])} for more
     * information on the order of execution.
     *
     * @see #execute(Object[])
     * @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
     */
    @MainThread
    public static void execute(Runnable runnable) {
        sDefaultExecutor.execute(runnable);
    }

即将任务体交给了sDeafaultExecutor,继续往下找,找到它的定义:


    /**
     * 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 final int MESSAGE_POST_RESULT = 0x1;
    private static final int MESSAGE_POST_PROGRESS = 0x2;

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

发现 sDefaultExecutor 引用了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);
            }
        }
    }

在这个对象里维护了一个任务队列

ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();

初次时mActive这个对象为空,执行完r.tun()方法后,再执行 if语句中的scheduleNext();
即从mTask这个取队头给mActive对象,下一个任务执行完就执行finally接口的scheduleNext();达到串行目的,而这个任务的最终执行是通过线程池执行的。

 THREAD_POOL_EXECUTOR.execute(mActive);

下面来分析,本类execute(final Runnable r) 这个r对象是从哪里传进来的,找到最初的调用之处:

 @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();

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }

这里就很明显了,枚举状态丢出了2个异常,分别对应任务正在执行与执行完成的异常:

 throw new IllegalStateException("Cannot execute task:"
                            + " the task is already running.");


throw new IllegalStateException("Cannot execute task:"
                            + " the task has already been executed "
                            + "(a task can be executed only once)");

文章开头处的连续出现异常最终原因也找到了。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值