AsyncTask源码简略分析

作者: Sanisy | 来源:发表于2016-07-17 11:14 被阅读108次

    要查看一个类实现的流程,我们需要先查看它类说明和成员变量。

    AsyncTask说明

    /**
     * <p>AsyncTask enables proper and easy use of the UI thread. This class allows to
     * perform background operations and publish results on the UI thread without
     * having to manipulate threads and/or handlers.</p>
     *
     * <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler}
     * and does not constitute a generic threading framework. AsyncTasks should ideally be
     * used for short operations (a few seconds at the most.) If you need to keep threads
     * running for long periods of time, it is highly recommended you use the various APIs
     * provided by the <code>java.util.concurrent</code> package such as {@link Executor},
     * {@link ThreadPoolExecutor} and {@link FutureTask}.</p>
    

    大概意思就是说AsyncTask可以很容易并且正确地结合UI线程,它可以将任务运行在后台并且将结果返回给UI线程,这个过程不需要使用任何专门的操纵UI的线程或者Handler。其实AsyncTask就是对Thread和Handler的一个封装。并且AsyncTask最好使用于需要很短执行时间的任务,非常耗时的任务应该使用Executor或者ThreadPoolExecutor加 FutureTask.

    AsyncTask的成员变量

        //很明显这是CPU的数量
        private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
        //这是线程池初始化线程数,为CPU数量加1
        private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
        //这是线程池维护的最大的线程数,CPU的两倍加1
        private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
        //当线程数超过初始化的线程数时,多出来的空闲线程,存活的时间是1秒,除非在等待过程中会有任务到来
        private static final int KEEP_ALIVE = 1;
        //用于构造线程池
        private static final ThreadFactory sThreadFactory = new ThreadFactory() {
            private final AtomicInteger mCount = new AtomicInteger(1);
    
            public Thread newThread(Runnable r) {
                return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
            }
        };
        //线程池的任务队列,最大同时存在128个任务
        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
                = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                        TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
    
        /**
         * An {@link Executor} that executes tasks one at a time in serial
         * order.  This serialization is global to a particular process.
         */
        //一个任务调度器,是串行性质的。意思是只有上一个任务完成了,才会调度分发一个新的任务
        public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
        //用于标志信息的类型,会在Message中使用
        private static final int MESSAGE_POST_RESULT = 0x1;
        private static final int MESSAGE_POST_PROGRESS = 0x2;
        
        //默认的执行线程池
        private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
        //用于返回结果或者传递进度给UI线程
        private static InternalHandler sHandler;
        //任务包装类,实现的是Callable接口。负责将doInbackground的任务包装
        private final WorkerRunnable<Params, Result> mWorker;
        //将WorkerRunnable进一步包装并且处理返回结果,实现的是RunnableFuture接口
        private final FutureTask<Result> mFuture;
    
    

    接下来我们看AsyncTask的入口execute(...)方法

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

    可以看到它是运行在主线程的方法,它调用的是executeOnExecutor(...),我们接着进入该方法。

        @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()方法,这个方法也是在主线程执行的。然后就执行Executor的execute()方法,这里传进去的是一个mFuture,前面我们知道它是一个RunnableFuture接口的实现类,它是在哪初始化的呢?答案是在AsyncTask的构造函数中

        /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
         */
        public AsyncTask() {
            mWorker = new WorkerRunnable<Params, Result>() {
                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<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);
                    }
                }
            };
        }
    

    初始化了mWorker,并且在call()方法中调用了doInBackground方法,并且调用了postResult方法。postResult其实就是返回结果给UI线程。

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

    我们来进去FutureTask里面,可以看到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);
            }
        }
    

    可以看到里面执行了callable的call()方法,然后设置了返回结果。在mFuture里面,done方法依然会做一个判断,判断该结果是否已经返回过了,如果没有返回则提交返回。

    说了这么多我们竟然没看到ThreadPoolExecutor的使用,好吧忘记说了。
    在说明execute方法时,我们说到了exec.execute(...),这个exec其实就是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);
                }
            }
        }
    

    可以看到里面设置了一个双端队列,来存储任务。在SerialExecutor的execute方法中,先是把FutureTask插入到了双端队列,然后判断这时候有没有任务正在执行,如果没有则通过scheduleNext()方法调度下一个任务给线程池THREAD_POOL_EXECUTOR去执行.

    我们来总结一下大概的流程:AsyncTask执行execute方法,首先调用的是onPreExecute方法,然后将执行参数传递给WorkerRunnable(是一个Callable的实现类),WorkerRunnable中call方法调用的是doInBackground方法,并处理了返回结果。然后FutureTask进一步封装了WorkerRunnable对象,然后将Future交给SerialExecutor去调度。SerialExecutor会把任务交给线程池去执行,线程池执行FutureTask的run方法,该方法其实就是取得WorkerRunnable的call方法。处理完成后检查结果是否已经在call方法中返回了,如果没有则提交返回。

    其实在3.0之前,任务默认是并发执行的。3.0之后串行执行,如果仍需要并发执行则可以通过executeOnExecutor方法来执行,而不是execute(...)方法。其实executeOnExecutor方法本质上就是绕过了SerialExecutor的调度,直接将任务提交给线程池。

    以前的版本

        private static final int CORE_POOL_SIZE = 5; 
        private static final int MAXIMUM_POOL_SIZE = 128; 
        private static final int KEEP_ALIVE = 10; 
      
        private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(10); 
    

    与以前相比,默认的线程池大小变了,现在是CPU数量+1
    任务队列也变了。由10变成128
    最大线程数原来是128,现在是2*CPU数+1
    以前是并发执行,现在是串行执行。

    相关文章

      网友评论

        本文标题:AsyncTask源码简略分析

        本文链接:https://www.haomeiwen.com/subject/dowujttx.html