美文网首页
AsyncTask 源码解析

AsyncTask 源码解析

作者: Batashi | 来源:发表于2018-05-23 12:01 被阅读0次

    一、前言
    AsyncTask是一个异步任务。里面封装了线程池及Handler。所以,它可以方便地实现线程的切换及耗时任务的执行。
    二、先上基本使用代码:

    class CusAsyncTask extends AsyncTask<Long, Integer, Long>
        {
            // 第一个执行的方法,可在此做些初始化操作。工作在主线程MainThread
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }
    
            // 此处执行耗时操作。工作在工作线程WorkerThread
            @Override
            protected Long doInBackground(Long... values)
            {
                long startTime = System.currentTimeMillis();
                for (int progress = 0; progress < values[0]; progress ++)
                {
                    // 此行代码会触发onProgressUpdate方法,实际使用中可用于进度更新
                    publishProgress(progress);
                }
               // 此处return 的结果会当成参数传递到 onPostExecute 中
                return System.currentTimeMillis() - startTime;
            }
    
            // 进度更新操作,由publishProgress来触发。执行在主线程MainThread
            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                Log.e("onProgressUpdate ", values[0] + "");
            }
    
            // 参数result实际上是doInBackground返回的结果。执行在主线程MainThread。可把结果
               直接显示到相关控件上
            @Override
            protected void onPostExecute(Long result) {
                super.onPostExecute(result);
                Log.e("onPostExecute ", "耗时 : " + result+ "ms");
            }
        }
    

    以下为调用方法:

    CusAsyncTask cusAsyncTask = new CusAsyncTask();
            // 并行运行
            cusAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 100L);
            // 串行运行
    //        cusAsyncTask.execute(100L);
    

    三、流程及原理分析
    1.先看看CusAsyncTask cusAsyncTask = new CusAsyncTask();都做了什么:

    /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI 
    thread.
    看到没有,初始化必须在UI线程也就是主线程中执行。
         */
        public AsyncTask() {
            this((Looper) null);
        }
        ......
    /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI
           thread.
         * 这是一个隐藏的函数。用于创建一个新的异步任务,由上面的构造函数所调用
         * @hide
         */
        public AsyncTask(@Nullable Looper callbackLooper) {
           // 这是必须要在主线程调用的原因,mHandler 需要主线程Handler
            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
                        // 线程执行的时候,实际上就是执行call方法。此时doInBackground启动
                        result = doInBackground(mParams);
                        Binder.flushPendingCommands();
                    } catch (Throwable tr) {
                        mCancelled.set(true);
                        throw tr;
                    } finally {
                        // 最终onPostExecute方法被回调,一个任务流程结束
                        postResult(result);
                    }
                    return result;
                }
            };
            // 封装了Callable
            mFuture = new FutureTask<Result>(mWorker) {
                // 当 Callable 的 call() 方法执行完毕之后调用
                @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.再看看cusAsyncTask.execute(100L)做了啥事。这样启动的任务是串行执行的

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

    其中,sDefaultExecutor实际上是一个自定义的线程池。且该线程池一次只能按排队顺序地执行一个任务(串行)。当然这是高版本,低版本3.0之前默认是并行的。

    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    /**
     * 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();
    
    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线程池来执行任务
                    THREAD_POOL_EXECUTOR.execute(mActive);
                }
            }
        }
    

    回到正题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()最先执行的原因
            onPreExecute();
    
            mWorker.mParams = params;
            // 把任务排到任务队列队尾。此时,任务正式执行
            exec.execute(mFuture);
    
            return this;
        }
    

    3.再看看并行启动的任务cusAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 100L);

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

    其中几个常量如下:

    // CPU核数,“设置——>关于手机”那里可以看到是几核。一般有4,6,8...
    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
    // 核心线程数为2到4之间,这些线程通常会一直活着,不会销毁
    private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
    // 最大线程数为:CPU核数 * 2 + 1。按目前的设备来看,一般在10-20左右
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    // 存活时间,即线程空闲时存活时间为30秒
    private static final int KEEP_ALIVE_SECONDS = 30;
    // 缓存任务数量最多128
    private static final BlockingQueue<Runnable> sPoolWorkQueue =
                new LinkedBlockingQueue<Runnable>(128);
    

    相关文章

      网友评论

          本文标题:AsyncTask 源码解析

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