1. 程式人生 > >AsyncTask原始碼分析

AsyncTask原始碼分析

1. 建立物件

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
	protected Long doInBackground(URL... urls) {
		int count = urls.length;
		long totalSize = 0;
		for (int i = 0; i < count; i++) {
			totalSize += Downloader.downloadFile(urls[i]);
			publishProgress((int) ((i / (float) count) * 100));
			// Escape early if cancel() is called
			if (isCancelled()) break;
		}
		return totalSize;
	}

	protected void onProgressUpdate(Integer... progress) {
		setProgressPercent(progress[0]);
	}

	protected void onPostExecute(Long result) {
		showDialog("Downloaded " + result + " bytes");
	}
}

DownloadFilesTask downloadTask = new DownloadFilesTask();

建立物件時,會呼叫AsyncTask的無引數構造:

    //Creates a new asynchronous task. This constructor must be invoked on the UI thread.
    public AsyncTask() {
        this((Looper) null);
    }

    //Creates a new asynchronous task. This constructor must be invoked on the UI thread.
    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);
                }
            }
        };
    }

1) mHandler

通過AsyncTask傳入的callbackLooper為null,則mHandler的值從getMainHandler方法中獲取。

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

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

建立sHandler時,用到了Looper.getMainLooper方法,說明sHandler和主執行緒的Looper繫結,sHandler的handlerMessage方法是執行在主執行緒中的。

    /**
     * Returns the application's main looper, which lives in the main thread of the application.
     */
    public static Looper getMainLooper() {
        synchronized (Looper.class) {
            return sMainLooper;
        }
    }

2) mWorker

private final WorkerRunnable<Params, Result> mWorker;

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

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

在建立mWorker物件時,實現了Callable介面的call方法,且call方法執行線上程池的某個工作執行緒中。此時會先執行doInBackGround方法,進而呼叫自己實現的doInBackGround方法。不管執行結果如何,都會執行postResult方法。故doInBackGround方法執行在子執行緒中。

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

    private Handler getHandler() {
        return mHandler;
    }

在工作執行緒總,通過mHandler發訊息,最終由mHandler的handlerMessage方法處理。因為mHandler和主執行緒的Looper繫結,mHandler的handlerMessage方法是執行在主線中的。

傳送的訊息id為MESSAGE_POST_RESULT,訊息內容為 new AsyncTaskResult<Result>(this, result) ,則靜態內部類的mTask為this,mData為doInBackGround方法的返回值result。


  private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;//傳入this,表示是當前AsyncTask
            mData = data;
        }
  }

在mHandler的handlerMessage方法中,最終會呼叫finish方法,若任務中間被取消,則執行onCancelled方法,否則執行onPostExecute方法。因為mHandler的handlerMessage方法是執行在主線中,則onCancelled/onPostExecute方法也都執行在主執行緒中。

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

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

    @MainThread
    protected void onPostExecute(Result result) {
    }

3) publishProgress

doInBackground方法用於後臺執行耗時任務,此時可以呼叫publishProgress更新進度

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

若沒有取消任務,則會發訊息,訊息id為MESSAGE_POST_PROGRESS,訊息內容為當前進度。

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

在mHandler的handlerMessage方法中,會呼叫onPorgressUpdate方法更新當前進度,且此時onPorgressUpdate方法是執行在主執行緒中的。

4) mFuture

mWorker作為引數,傳入FutureTask,不管執行完畢,還是中途取消任務,都會執行重寫的done方法,進而執行postResultIfNotInvoked方法。

    private final FutureTask<Result> 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);
                }
            }
        };

因為在2)中的Call方法中把mTaskInvoked置為了true,此時不會執行postResult方法。

    private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

2 執行

downloadTask.execute(url1, url2, url3);

此時會呼叫executeOnExecutor方法

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

mStatus有PENDING、RUNNING、FINISHED三種狀態,若此時不處於PENDING狀態,就會報錯。這也就是為什麼多次呼叫同一個AsyncTask物件會報錯。一個物件只能執行一次任務,若需要執行其他任務,則要再建立物件,這也就是為什麼AsyncTask是輕量級的非同步類。

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

開始執行任務前會先呼叫onPreExecute()方法,可進行顯示進度條等UI操作,因為此方法執行在主執行緒中。

真正執行任務的是exec.execute(mFuture)方法,也就是sDefaultExecutor的execute(mFuture)方法。

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

        protected synchronized void scheduleNext() {
            if ((mActive = mTasks.poll()) != null) {
                THREAD_POOL_EXECUTOR.execute(mActive);
            }
        }
}

public interface Executor {

    /**
     * Executes the given command at some time in the future.  The command
     * may execute in a new thread, in a pooled thread, or in the calling
     * thread, at the discretion of the {@code Executor} implementation.
     *
     * @param command the runnable task
     * @throws RejectedExecutionException if this task cannot be
     * accepted for execution
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);
}

也就是執行mFuture的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);
        }
    }

因為mWorker作為Callable型別的引數,傳入了mFuture,會先執行mFuture的call方法,也就是doInBackground方法,把後臺處理結果返回,置ran為true。接著呼叫set(result)方法

    protected void set(V v) {
        if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {
            outcome = v;
            U.putOrderedInt(this, STATE, NORMAL); // final state
            finishCompletion();
        }
    }

又會呼叫到finishCompletion方法,接著執行done方法,就會執行到mFuture的done方法。在finishCompletion方法內會把callable置null。

    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
    }

如果在呼叫了AsyncTask的execute方法後立馬就執行了AsyncTask的cancel方法(實際執行mFuture的cancel方法),那麼會執行done方法,且捕獲到CancellationException異常,從而執行語句postResultIfNotInvoked(null),由於此時還沒有來得及執行mWorker的call方法,所以mTaskInvoked還未false,這樣就可以把null傳遞給postResult方法。

3 執行緒池

AsyncTask中使用了執行緒池,快取了一定數量的執行緒,避免了不斷建立、銷燬執行緒帶來的開銷,提高了效能。

    //本機處理器的核心數
    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
    //AsyncTask所使用的執行緒池的核心執行緒數
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    //AsyncTask所使用的執行緒池的最大執行緒數:2被核心數+1
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE_SECONDS = 30;

    //例項化執行緒工廠ThreadFactory,sThreadFactory用於在後面建立執行緒池
    private static final ThreadFactory sThreadFactory = new ThreadFactory() {
        //AtomicInteger是一個提供原子操作的Integer類,確保了其getAndIncrement方法是執行緒安全的
        private final AtomicInteger mCount = new AtomicInteger(1);

        //重寫newThread方法的目的是為了將新增執行緒的名字以"AsyncTask #"標識    
        public Thread newThread(Runnable r) {            
            return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
        }
    };

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

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