AsyncTask原理

构造方法中创建了一个WorkRunnable和一个FutureTask对象,

在WorkRunnable的Call方法中调用doInBackground方法,并获取Result返回值,然后返回调用postResult方法的返回值,创建FutureTask时传入了WorkRunnable对象,

public AsyncTask() {
    mWorker = new WorkerRunnable() {
        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(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);
            }
        }
    };
}
postResult方法

getHandler方法获取自带Handler对象,来获取Message

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

这个内部自带InternalHandler构造方法中传入getMainLooper()返回值,即主线程Looper,

然后在handlerMessage里面针对msg.what分别执行了finish和onProgressUpdate方法,其中finish方法则是调用onCancelled或onPostExecute方法

private static final InternalHandler sHandler = new InternalHandler();

private static class InternalHandler extends Handler {
    public InternalHandler() {
        super(Looper.getMainLooper());
    }

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


看看AsyncTask的execute方法,返回了executeOnExecutor的方法,并传入sDefaultExecutor和params为参数,params即AsyncTask的doInBackground中传入的params

而sDefaultExecutor是默认的串行执行器(线程池),一个SerialExecutor
再看看executeOnExecutor方法,先判断了任务状态,如果是RUNNING或FINISHED,则会抛出异常,

然后会把当前状态从PENDING改为RUNNING,把入参params传到WorkRunnable对象中,再调用传入的sDefaultExecutor的execute方法,传入mFuture为参数

public final AsyncTask 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;
}

execute方法中调用mTasks的offer方法添加一个任务到缓存队列中,在run方法中就调用了前面传入的mFuture的run方法,

然后执行THREAD_POOL_EXECUTOR的execute方法,任务的实际执行就在这,THREAD_POOL_EXECUTOR就是一个线程池

private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

public static final Executor SERIAL_EXECUTOR = new SerialExecutor();

private static class SerialExecutor implements Executor {
    final ArrayDeque mTasks = new ArrayDeque();
    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);
        }
    }
}

你可能感兴趣的:(学习)