跨进程通信

Android 异步任务知识梳理(1) - AsyncTask

2017-02-20  本文已影响98人  泽毛

一、概述

这篇文章中,让我们从源码的角度看一下AsyncTask的原理,最后会根据原理总结一下使用AsyncTask中需要注意的点。

二、源码解析

AsyncTask中,有一个线程池 THREAD_POOL_EXECUTOR 和与这个线程池相关联的 Executor,它负责执行我们的任务Runnable

private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;

private static final ThreadFactory sThreadFactory = new ThreadFactory() {    
    private final AtomicInteger mCount = new AtomicInteger(1);    
    public Thread newThread(Runnable r) {        
        return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());    
    }
};

private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128);

public static final Executor THREAD_POOL_EXECUTOR 
    = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);

public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

//这是执行Runnable的地方,调用execute会执行它,如果当前已经有一个任务在执行,那么就是把它放到队列当中。
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();                
                }            
             }        
        });
        //如果为null,那么立刻执行它;
        //如果不为null,说明当前队列中还有任务,那么等Runnable执行完之后,再由上面的scheduleNext()执行它。        
        if (mActive == null) {               
            scheduleNext();        
        }    
   }    

   protected synchronized void scheduleNext() {
        //第一次进来调用了offer方法,因此会走进去,执行上面Runnable的run()方法。        
        if ((mActive = mTasks.poll()) != null) {            
           THREAD_POOL_EXECUTOR.execute(mActive);        
        }    
    }
}

从上面可以看出,每次调用sDefaultExecutor.execute时就是执行一个任务,这个任务会被加入到ArrayDeque中串行执行,我们看一下当我们调用AsyncTaskexecute方法时,任务是如何被创建并加入到这个队列当中的:

//这个静态方法,不会回调 loadInBackground 等方法。
public static void execute(Runnable runnable) {    
    sDefaultExecutor.execute(runnable);
}

//这是我们最常使用的方法,参数可以由调用者任意指定。
public final AsyncTask<Params, Progress, Result> execute(Params... params) {    
    return executeOnExecutor(sDefaultExecutor, params);
}

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

在调用了executeOnExecutor之后,我们把传入的参数赋值给了mWorker,并把mFuture传入给Executor去执行,而从下面我们可以看到mFuture的构造函数中传入的参数正是mWorker,这两个东西其实才是AsyncTask的核心,它们是在AsyncTask的构造函数中被初始化的:

private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;

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 {
            //要求mWorker的call方法没有被调用,否则什么也不做。            
            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);        
       }    
   }
};

先看一下WorkerRunnable,实现了Callable<V>接口,增加了一个不定参数的成员变量用来传给 doInBackground,这个不定参数就是我们在execute时传入的,调用call时会执行器内部的函数,而call 时会调用doInBackground方法,这个方法执行完之后,调用postResult,注意到calldone都是在子线程当中执行的:

private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {    
    Params[] mParams;
}

我们主要看一下FutureTask,还记得最开始我们的Executor最终执行的是传入的Runnablerun方法,因此我们直接看一下它的run方法中做了什么:

public interface Runnable {
   public void run();
}

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;
}

public interface RunnableFuture<V> extends Runnable, Future<V> { 
    void run();
}

//我们只要关注run方法
public class FutureTask<V> implements RunnableFuture<V> {
    public void run() {
        Callable<V> c = callable;
        if (c != null && state == NEW) {
            result = c.call(); //mWorker.call()
            ran = true;
        }
        if (ran) {
            set(result);
        }
    }

    protected void set(V v) {
        finishCompletion();
    }

    private void finishCompletion() {
        done(); //mFuture.done()
        callable = null;
    }
}

那么结论就清晰了,整个的执行过程是下面这样的:

在上面的过程当中,有两个地方都调用了postResult,一个是mWorkder#call的最后,另一个是mFuture#done,但是区别在于后者在调用之前会判断mTaskInvokedfalse时才会去执行,也就是在mWorkder#call没有执行的情况下,这是为了避免call方法没有被执行时(提前取消了任务),postResult没有被执行,导致使用者收不到任何回调。
postResult会通过InternalHandler把当前的AsyncTaskFutureTask的结果回调到主线程当中,之后调用finish方法,它会根据调用者是否执行过cancel方法来回调不同的函数:

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

调用者通过重写onProgressUpdate就可以得到当前的最新进度,AsyncTask最终会把结果回调到主线程当中:

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

private static class InternalHandler extends Handler {
    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;
        }
    }
}

三、结论

经过上面的源码分析,我们有这么几个结论:

上一篇下一篇

猜你喜欢

热点阅读