最全面的AsyncTask源码解析,解决你的面试疑惑

AsyncTask相信大家并不陌生,它是android官方给我们提供的处理异步任务更新UI的API,使用它可以非常灵活的在子线程中执行任务,然后在UI线程中更新UI。

一、简单使用

1、继承AsyncTask抽象类实现doInBackground方法

public class DownloadAsyncTask extends AsyncTask {

    private static final String TAG = "DownloadAsyncTask";

    /**
     * 异步任务开始时
     * 工作在主线程
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    /**
     * 异步任务结果的回调
     * 工作在主线程
     *
     * @param o
     */
    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);

        Log.d(TAG, "  onPostExecute " + o.toString());
    }

    /**
     * 异步任务执行的属性
     * 工作在主线程
     *
     * @param values
     */
    @Override
    protected void onProgressUpdate(Object[] values) {
        super.onProgressUpdate(values);
    }

    /**
     * 执行异步任务的方法
     * 工作在主线程
     *
     * @param objects
     * @return
     */
    @Override
    protected Object doInBackground(Object[] objects) {
        Log.d(TAG, "  doInBackground " + objects[0].toString());
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "reslut";
    }
}

2、执行异步任务

DownloadAsyncTask downloadAsyncTask = new DownloadAsyncTask();
downloadAsyncTask.execute("我是参数1","我是参数2");

是不是很简单啊,onPreExecute在准备阶段被调用,异步任务执行开始后,doInBackground在子线程执行异步任务,执行的结果通过return返回到UI线程的onPostExecute方法中执行UI更新,如果是下载或者上传任务,还可以在onProgressUpdate 执行任务的更新。那AsyncTask是怎么实现的呢?让我们翻一下源码看看它到底是怎么做的。

二、源码解读

1、downloadAsyncTask.execute

public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        //1、点击execute方法直接跳转到这里,有一个sDefaultExecutor
        return executeOnExecutor(sDefaultExecutor, params);
}

@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)");
        }
    }
    //将状态设置为running状态
    mStatus = Status.RUNNING;
    //调用开始执行的回调
    onPreExecute();

    //将需要执行的参数传递给mWorker
    //????为什么要给mWorker
    mWorker.mParams = params;

    //在子线程中执行mFuture
    //????mFuture是什么鬼
    exec.execute(mFuture);

    return this;
}

从上面的asynctask执行方法中可以看到,调用了一个默认线程池去执行的, 因此我们也得到三个问题?

1、sDefaultExecutor怎么来的?
2、参数为什么要给mWorker
3、mFuture是什么鬼

要知道上面的问题,我们需要找到这些变量都是怎么被创建的。想想我们一共就执行了两步,初始化和执行两个方法,那么一定是在构造函数中创建的这些变量。下面看看构造函数的源码。

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

从方法的注释可以看到,这个方式是一个Asynctask的构造函数,且一定是在UI线程执行。另外创建了3个变量mHandlermWorkermFuture。其中mWorker 作为一个参数传递到了mFuture 里面。这里正好解答了前一个问题,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)");
        }
    }
    //1、将状态设置成RUNNING状态
    mStatus = Status.RUNNING;
    //2、调用AsyncTask的第一个回调方法,代表这个asynctask将要执行,在这里可以做一个初始化的操作
    onPreExecute();
    //3、将参数传递给mWorker, 这个mWorker 最终传递给了mFuture
    mWorker.mParams = params;
    //4、调用执行方法  exec是什么   
    exec.execute(mFuture);

    return this;
}

接下来看看exec的源码。

// 第一步
executeOnExecutor(sDefaultExecutor, params);
// 第二步
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
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();
        }
    }

    //最终调用的是一个线程获取的线程来执行Runnable
    //这里留下一个问号,为什么是synchronized 修饰以及mActive = mTasks.poll()
    protected synchronized void scheduleNext() {
        if ((mActive = mTasks.poll()) != null) {
            THREAD_POOL_EXECUTOR.execute(mActive);
        }
    }
}

可以看到asynctask的执行方法,最终调用的是SerialExecutor 这个静态内部类的execute,并且把构造方法中的mFuture中也传递过来了,并且通过mTasks.offer将一个Runnable回调传递进来了。mTasks是一个装载任务的数组。最后调用了一个scheduleNext();方法,这个方法内部其实是一个线程池。

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

接下来执行的就是线程的run方法,内部调用了mFuture的run方法。再回过头去看asynctask方法的构造里面的mFuture的初始化。

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

//查看它的构造方法
 public FutureTask(Callable<V> callable) {
     if (callable == null)
         throw new NullPointerException();
     this.callable = callable;
     this.state = NEW;       // ensure visibility of callable
 }

这里可以看到做了两件事,一是将mWorker赋值给了callable ,并将状态设置成了NEW,接下来去看它的run方法。

 public void run() {
    if (state != NEW ||
        !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))
        return;
    try {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            V result;
            boolean ran;
            try {
                result = c.call();
                ran = true;
            } catch (Throwable ex) {
                result = null;
                ran = false;
                setException(ex);
            }
            if (ran)
               //得到结果以后
                set(result);
        }
    } finally {
        // runner must be non-null until state is settled to
        // prevent concurrent calls to run()
        runner = null;
        // state must be re-read after nulling runner to prevent
        // leaked interrupts
        int s = state;
        if (s >= INTERRUPTING)
            handlePossibleCancellationInterrupt(s);
    }
}

//执行回调结果
protected void set(V v) {
    if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
        outcome = v;
        U.putOrderedInt(this, STATE, NORMAL); // final state
        finishCompletion();
    }
}
//执行回调结果,最终调用done 也就是mFuture的done,最后调用postResultIfNotInvoked
private void finishCompletion() {
    // assert state > COMPLETING;
    for (WaitNode q; (q = waiters) != null;) {
        if (U.compareAndSwapObject(this, WAITERS, q, null)) {
            for (;;) {
                Thread t = q.thread;
                if (t != null) {
                    q.thread = null;
                    LockSupport.unpark(t);
                }
                WaitNode next = q.next;
                if (next == null)
                    break;
                q.next = null; // unlink to help gc
                q = next;
            }
            break;
        }
    }
    done();

    callable = null;        // to reduce footprint
}

最后调用的就是mWorker.call这个方法。在回头去看mWorker和mFuture的初始化方法

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

private void postResultIfNotInvoked(Result result) {
    final boolean wasTaskInvoked = mTaskInvoked.get();
    if (!wasTaskInvoked) {
        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;
}

相信在这里我们会看到很熟悉的方法,一个是result = doInBackground(mParams); 和 postResult(result);猜想一下就是我们使用最多的两个方法,一个执行耗时任务的方法, 一个得到运行结果的方法。

//方法一
protected abstract Result doInBackground(Params... params);
//方法二
postResultIfNotInvoked(get());

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

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
                //看这里也知道是最后的结果,看看finish最后的执行
                result.mTask.finish(result.mData[0]);
                break;
            case MESSAGE_POST_PROGRESS:
                result.mTask.onProgressUpdate(result.mData);
                break;
        }
    }
}

//最后执行了我们最常用到的onPostExecute方法
private void finish(Result result) {
    if (isCancelled()) {
        onCancelled(result);
    } else {
        onPostExecute(result);
    }
    mStatus = Status.FINISHED;
}

截止到这里,我们了解到asynctask的最终的实现原理,就是定义一个mWorker里面包含了onPostExecutedoInBackground``两个重要的回调方法的执行,然后将mWorker“传递给一个mFutureTask的变量作为参数。并将mFutureTask变量作为参数传递给一个SerialExecutor去执行,执行的实质就是从线程池取一个线程执行mFutureTaskrun方法,而它的run方法最终的实质是执行mWorkerrcall方法,其实就是doInBackgroundonPostExecute方法。最后使用handler异步发送消息,调用主线程的onPostExecute。这样一个完成的异步执行流程就结束了。
简单说就是线程池取一个线程,执行完任务,使用handler发送消息到主线程做更新。
有个小疑问就是在使用线程池这一步骤的时候,绕了很大一圈。是为了解决什么问题呢?下面来观察一个细节问题。在执行任务的时候调用了一个这个方法

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

这里SerialExecutor 使用的是静态变量,也就是说所有的AsyncTask使用默认的闯将方式的话,就共用了一个SerialExecutor 实例,它内部是维持的是一个队列数组。同时使用了同步锁和队列数组保证了asynctask的串行执行。曾经的一个面试题,当时我没有回答上来。

另外一个面试题。
关于AsyncTask内存泄漏的问题。
原因在于我们在使用asynctask多使用创建内部类,默认内部类会持有外部类的引用,而外部类是activityfragment造成其不能回收,从而出现内存问题。其实这个解释并不好,还有人说单独创建一个类继承asynctask然后使用回调来处理更新UI,这是我在面试别人的时候,给出的答案。 其实这些都是没有了解到asynctask造成内存问题的本质。
本质就是asynctask内部使用的是一个线程,执行异步任务。不管你是内部类持有activity引用还是回调使用textview.settext类似的更新,textview本身也持有context上下文引用,所以外部类调用根本解决不了问题。原因是线程异步调用是一个未知的,你不知道它什么时候结束,如果不结束,它就只有只有activity或者context引用,造成整个页面的对象不能得到释放。如果大量的使用,就容易造成内存泄漏。 积累比较多以后,就容易造成更严重内存溢出。

解决AsyncTask的内存泄漏的方法就是使用静态内部类加软引用的方式解决。 静态内部类保证了不持有外部类的引用,但是需要使用外部类的引用去做UI更新,所以需要传入一个外部类引用,但是这样做又回到了最初持有外部类引用的状况,所以这时候需要使用软引用包裹外部类引用,做到GC想回收就回收。Handler引起的内存泄漏也可以使用这个方式来解决。

发布了58 篇原创文章 · 获赞 16 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/dingshuhong_/article/details/80596499