AsyncTask

AsyncTask通常有以下兩種調用方式:

1. AsyncTaskImpl().setTask(RunnableImpl).execute();
2. AsyncTask.execute(RunnableImpl);
  • 僅針對第一種方式進行分析:
AsyncTask.AsyncTask():
public AsyncTask() {  
    /**
     * 1. 初始化AsyncTask時會在主線程中創建WorkerRunnable和FutureTask對象;
     * 2. 先跳過FutureTask, 直接分析execute(), 然后從execute()分析FutureTask;
     */
    mWorker = new WorkerRunnable<Params, Result>() {...};
    mFuture = new FutureTask<Result>(mWorker) {...};
}
WorkerRunnable :
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
    Params[] mParams;
}
public interface Callable<V> {
    V call() throws Exception;
}
AsyncTask.execute() :
public class AsyncTask {
    public final AsyncTask<...> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    private static class SerialExecutor implements Executor {...}
}
AsyncTask.executeOnExecutor() :
public class AsyncTask {
    public final AsyncTask<...> executeOnExecutor(Executor exec, ...) {
        /**
         * 1. mStatus初始化時被賦值Status.PENDING, 由下文可知沒Status只有三個可
         * 能的值: PENDING/RUNNING/FINISHED, 當前任務執行完畢, mStatus被賦值
         * FINISHED, 當任務執行中時RUNNING, 所以當再次調用execute()時, 會拋出異
         * 常, 這種方式下的AsyncTask僅僅適合單個任務, 不適
         * 用于多線程的場景;
         * 2. 如果想要按順序的執行多個AsyncTask, 可以使用方式2_AsyncTask.execute(RunnableImpl);
         */
        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;
        /**
         * FutureTask的分析從此揭開序幕;
         */
        exec.execute(mFuture);
        return this;
    }
}
AsyncTask.mFuture :
public class AsyncTask {
    public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    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 static class SerialExecutor implements Executor {
        final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
        Runnable mActive;
        /**
          * 由ArrayDeque內部結構可以知道當執行一個Runnable時, 會先將改Runnable添
          * 加至ArrayDeque內部數組的尾部, 然后從數組的頭部讀取Runnable執行, 即按
          * 照FILO的方式;
          */
        public synchronized void execute(final Runnable r) {
            /**
             * 對于方式1, 也僅考慮方式1(方式2直觀沒有什么地方值得研究);  此時Runnable
             * 實際指向mFuture, 而mFuture內部又持有WorkerRunnable的引用;
             * mActive實際指向mFuture;
             * 這里主要用到了適配器的模式;
             */
            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);
            }
        }
    }
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
    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 class FutureTask<V> implements RunnableFuture<V> {
    public FutureTask(Callable<V> callable) {
        this.callable = callable;
        this.state = NEW;   
    }
    public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW; 
    }
    public void run() {
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                result = c.call();
                ran = true;
                if (ran)
                    set(result);
            }
        } 
    }
}

??這里用到了適配器模式, FutureTask有兩個構造函數分別可以接收Callable與Runnable, 但是對外之暴露了一個run()的接口供調用, 如果傳的是Callbale, run方法調用了c.call()方法. 如果傳入的是Runnable, run()方法則會一波三折, 他先調用c.call()方法, 此時c實際是RunnableAdapter implements Callable, 然后調用的是RunnableAdapter中的call()方法, 然后里面又調用了Runnable的run()方法, 此Runnable就是我們傳入的Runnable對象;

public class Executors {
    public static <T> Callable<T> callable(Runnable task, T result) {
        return new RunnableAdapter<T>(task, result);
    }
    static final class RunnableAdapter<T> implements Callable<T> {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {
            task.run();
            return result;
        }
    }
}

?? 其實感覺AsyncTask本身是挺簡單的, 關鍵在于他對線程的操控, 這個需要注意一下. 這個現在是真心沒法看下去了, 等我把幾本關于底層的書看完在說這些事兒吧;

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容