android AsyncTask 源码跟踪

android 处理异:AsyncTask

new MyAysnTask("AysnTask-1").execute("");

如何实现的就不写了,自行百度,下面来看一下execute方法:

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

可见execute里面又调用了executeOnExecutor(),这个是方法是通过一个线程池来执行,sDefaultExecutor是AsyncTask一个默认的线程池:串行线程池类

    private static final int CPU_COUNT = 
    Runtime.getRuntime().availableProcessors();
    //至少2个线程和最多4个线程在核心池中
    // 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
    private static final int CORE_POOL_SIZE = Math.max(2, 
    Math.min(CPU_COUNT - 1, 4));
    private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
    private static final int KEEP_ALIVE_SECONDS = 30;

    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;//默认线程池
    }

private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;

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(E e) 在队列尾部添加一个元素,并返回是否成功
         mTasks.offer(new Runnable() {
                public void run() {
                    try {
                      //等待执行
                        r.run();
                    } finally {
                        //执行下一个调度线程,这样在一个队列中就实现了串行调度
                        scheduleNext();
                    }
                }
            });
           //首次执行
            if (mActive == null) {
                scheduleNext();
            }
        }

        protected synchronized void scheduleNext() {
        //poll()  删除队列中第一个元素,并返回该元素的值,如果元素为null,
        //将返回null(其实调用的是pollFirst())
            if ((mActive = mTasks.poll()) != null) {
              //取一个任务。不为空就执行。
                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();
        mWorker.mParams = params;
        exec.execute(mFuture);
        return this;
    }

没完。。。。。。。。。。。。。。。。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容