AsyncTask工作原理
从AsyncTask的execute方法入手:
@MainThread public final AsyncTask<Params, Progress, Result> execute(Params... params) { 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)"); } } mStatus = Status.RUNNING; onPreExecute(); //首先执行onPreExecute() mWorker.mParams = params; //将参数封装为mWorker的相关参数 exec.execute(mFuture); //串行执行Task return this; }
sDefaultExecutor是一个串行的线程池,一个进程汇总的所有AsyncTask全部在这个线程池中排队执行。
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() { //将FutureTask对象插入到任务队列中 public void run() { try { r.run(); } finally { scheduleNext(); } } }); if (mActive == null) { //如果没有正在活动的任务,那么就调用scheduleNext()来执行下一个任务 scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } }
线程池THREAD_POOL_EXECUTOR用于真正的执行任务,InternalHandler用于将执行环境从线程池切换到主线程。
mWorker = new WorkerRunnable<Params, Result>() { //FutureTask的run方法会调用mWorker的call()方法,因此mWorker的call方法最终会在线程池中执行。 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; } };
sHandler是一个静态Handler对象,sHandler收到MESSAGE_POST_RESULT这个消息后悔调用AsyncTask的finish方法.
以上内容为阅读《Android开发艺术探索》总结。
时间: 2024-11-12 06:26:15