AsyncTask源码解析干货

作者: tiloylc | 来源:发表于2018-03-12 17:18 被阅读0次

前言

好久没看过源码了,前几天面试被问到一脸懵逼,全忘掉了。复习一下,做个笔记分享。AsyncTask是android开发中一个非常重要的异步类,可以在异步线程中做一些耗时的操作。本文参照源码对AsyncTask进行简单的解析。

一、AsyncTask简介及基本使用。

1、AsyncTask简介

  AsyncTask是对针对Handler+线程池的封装,可以在异步的去更新UI,使用方式简单便捷,仅需要继承AsyncTask抽象类,并实现几个基本方法即可,需要注意的是必须要在UI线程进行调用,因为AsyncTask使用的Handler为UI线程 下的Handler,只有这样才可以在子线程去更新UI线程。
  AsyncTask类的声明如下:

public abstract class AsyncTask<Params, Progress, Result> 

其中:
 Params为传入到doInBackground方法的参数类型;
 Progress为进度条所使用的参数类型;
 Result为线程完成后返回值的参数类型;
AsyncTask主要的方法有五个:

onPreExecute() : 在线程池开始进行任务之前调用,为准备工作

doInBackground(Params… params) :线程中进行的工作,唯一一个在子线程运行的方法

onProgressUpdate(Progress… values):显示线程中工作进度,调用方法在doInBackground中的
publishProgress方法

onPostExecute(Result result) :线程结束后会通过handler调用到onPostExecute方法,并返回结果

cancel(boolean mayInterruptIfRunning):中途打断线程运行,但不一定会成功。如果任务已经完成,
则无论mayInterruptIfRunning为true还是false,此方法肯定返回false,即如果取消已经完成的任务会
返回false;如果任务正在执行,若mayInterruptIfRunning设置为true,则返回true,若mayInterruptI
fRunning设置为false,则返回false;如果任务还没有执行,则无论mayInterruptIfRunning为true还是
false,肯定返回true。

2、AsyncTask注意事项

1、AsyncTask并不会随Activiy关闭而取消,doInbackground依然会运行,直到线程结束后会调用finish()方法,如果在关闭前调用过cancel()方法,会调onCancelled()方法,如果没有的话,会直接跳转OnPostExecute()方法,可能会导致AsyncTask报错崩溃。

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

2、如果屏幕旋转或其他方式导致Activity重新创建,那么AsyncTask所持有的Activity中的引用会失效,OnPostExecute()方法绘制的时候将不会有效果。
3、要注意并行和串行,分别由execute()和executeOnExecutor(Executor)控制。

3、源码分析

AsyncTask构造器:

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

很明显,在构造器中new了两个对象,分别为WorkerRunnable和FutureTask(FutrueTask为java并发编程中一个比较重要类,如果不了解的话,请百度一下,或者看我下一篇文章)。doInBackground()方法在mWorker的call()方法中被调用,且返回值在postResult()方法中被调用。
我们来看一下WorkerRunnable类的源码和FutureTask的构造方法。

private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
 public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

很明显,WorkerRunnable类实现了Callable的接口。被FutureTask作为参数传入。这就说明doInbackground()实际是在异步线程中被调用。且实际上AsyncTask的成员mWorker包含了AyncTask要执行的任务。那么mWorker的call()方法到底什么时候会被调用呢,了解过FutureTask运行机制的朋友都知道FutureTask只有被放到线程池中的时候才会被调用,进而调用到call()方法。
在看一下刚刚注意事项里说道的execute()方法的源码:

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

由源码可以,该方法仅能在主线程中使用,另外execute返回的是executeOnExecutor方法的返回值,参数为sDefaultExecutor和params。
首先来看下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();

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

        return this;
    }

第一个参数为线程调度的对象,第二个参数为mWorker的mParams参数,由上面的源码可知,mParams参数是传到doInBackground中的。另外executeOnExecutor()方法中还调用了onPreExecute(),之后才会调用exec.execute(mFuture);说明onPreExecute方法的确是在主线程中调用,且在子线程开始之前调用。
我们再看看sDefaultExecutor参数:

 public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
 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);
            }
        }
    }

很简单,sDefaultExecutor 为SerialExecutor类 的一个对象,且标识为volatile,以防止线程问题。SerialExecutor 的实现中可以看到,线程池维持了一个Runnable的队列。mActive为正在运行的线程,当调用execute()方法时在队列末尾插入需要运行的Runnable对象。并调用scheduleNext();方法。如果当前运行的Runnable对象为空的话,会继续调用scheduleNext(),在scheduleNext()方法中可以看到首先mTasks出队给mActive赋值,如果不为空,则
  THREAD_POOL_EXECUTOR.execute(mActive)
我们来看一下THREAD_POOL_EXECUTOR是什么

  /**
     * 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;
    }

可以看出来THREAD_POOL_EXECUTOR是一个线程池对象,为真正开始异步逻辑的载体。

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
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; 
private static final int KEEP_ALIVE_SECONDS = 30;

由注释可以看出,编写者希望线程池基本大小(CORE_POOL_SIZE )最少为2个线程,最多为4个线程,来维持线程池的运转,只有在队列满的时候才会创建更多的线程。线程池中允许的最大线程数(MAXIMUM_POOL_SIZE )为CPU的数目的2倍+1,线程空闲时超时时间(KEEP_ALIVE_SECONDS )为30s。
另外在上面说过当WorkerRunnable任务做完的时候会调用postResult()方法。看一下源码

  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中处理

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

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

如果为MESSAGE_POST_RESULT,则会调用finish()方法,在上文中已经说到过该方法,由构造方法可以看出,InternalHandler使用的为主线程的looper,故而可以在handleMessage中刷新UI。
另外还有一个publishProgress:

 @WorkerThread
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

也是通过message通知handler刷新UI。

如果有什么问题欢迎留言或给我发邮件 tlioylc@gmail.com
良心干货,欢迎关注

相关文章

  • Android AsyncTask 源码解析

    标签:Android AsyncTask 源码解析 1.关于AsyncTask 1.1 什么是AsyncTask?...

  • AsyncTask源码解析干货

    前言 好久没看过源码了,前几天面试被问到一脸懵逼,全忘掉了。复习一下,做个笔记分享。AsyncTask是andro...

  • 4.AsyncTask使用,原理

    资料 AsyncTask处理机制详解及源码分析-工匠若水 AsyncTask 源码解析-鸿洋 带你认识不一样的As...

  • Android日记之AsyncTask源码解析

    前言 AsyncTask的使用方法请看Android日记之AsyncTask的基本使用,此篇的源码解析我们还是从使...

  • AsyncTask原理解析

    AsyncTask是一个串行的线程,本文主要通过源码解析它的原理 -->从 AsyncTask执行的方法execu...

  • AsyncTask 源码解析

    一、前言AsyncTask是一个异步任务。里面封装了线程池及Handler。所以,它可以方便地实现线程的切换及耗时...

  • AsyncTask源码解析

    参考资料:Android开发艺术探索 AsyncTask是一个Android官方提供的一种轻量级的异步任务类,它可...

  • AsyncTask源码解析

    AsyncTask 执行轻量级的异步任务,将结果传递给主线程,主线程根据结果更新UI. 使用 AsyncTask创...

  • AsyncTask源码解析

    AsyncTask源码解析 最近再刷一些基础的东西,所以就随便记录了一些看源码的心得,目前开发中见到了很多Asyn...

  • AsyncTask源码解析

    参考资料 鸿洋版AsyncTask郭霖版AsyncTask线程池Android开发艺术探索Android源码 相关...

网友评论

    本文标题:AsyncTask源码解析干货

    本文链接:https://www.haomeiwen.com/subject/kgnnfftx.html