AsyncTask原理解析

AsyncTask是一个串行的线程,本文主要通过源码解析它的原理

-->从 AsyncTask执行的方法execute开始

 @MainThread
    public final AsyncTask execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }
  • @MainThread注解表示该方法只能在UI线程中执行
  • 传入一个sDefaultExecutor

--> executeOnExecutor方法中执行sDefaultExecutor.execute(mFuture)

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

-->sDefaultExecutor实际上是一个SerialExecutor对象,所以最终执行了SerialExecutor的execute方法

  public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    @UnsupportedAppUsage
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

-->SerialExecutor的execute逻辑

  • ArrayDeque数组存放任务
    ArrayDeque是一个实现了Deque接口的AbstractCollection,所以是一个具有双端队列属性的集合。
    关于ArrayDeque:https://www.jianshu.com/p/b29a516eb322
  • synchronized修饰excute方法,所以实现线程的串行
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);
            }
        }
    }

---->ArrayDeque中在此双端队列的末尾插入指定的元素。
  public boolean offer(E e) {
        return offerLast(e);
    }

总结

  • AsyncTask是通过Synchronize关键字实现线程安全的
  • AsyncTask中通过ArrayDeque双端队列集合存储需要执行的任务
  • 在双端队列的末尾插入需要执行的元素。

你可能感兴趣的:(AsyncTask原理解析)