zoukankan      html  css  js  c++  java
  • Android AsyncTask 分析内部实现

    sdk3.0前,使用内部的线程池,多线程并发运行。线程池大小等于5,最大达128

    sdk3.0后,使用默认的serial线程池。运行完一个线程,再顺序运行下一个线程。sdk3.0<=current version <= sdk4.3时 线程池大小等于5,最大达128

    sdk4.4后线程池大小等于 cpu count + 1。最大值为cpu count * 2 + 1

    sdk3.0后有两种线程池的实现,默觉得 Serial 线程池

    public static final Executor SERIAL_EXECUTOR = new SerialExecutor();
    public static final Executor THREAD_POOL_EXECUTOR
                = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                        TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
    private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
    public static void setDefaultExecutor(Executor exec) {//设置默认线程池
            sDefaultExecutor = 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);
                }
            }
        }

    THREAD_POOL_EXECUTOR 并发线程池

    asynctask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR); //设置使用 并发线程池 

    //params 都是使用在doInBackground(Params... params);

    asynctask.executeOnExecutor(executor, params); //能够自己定义 线程池     使用这两种方法

  • 相关阅读:
    November 13th 2016 Week 47th Sunday The 1st Day
    November 12th 2016 Week 46th Saturday
    November 11th 2016 Week 46th Friday
    November 10th 2016 Week 46th Thursday
    November 9th 2016 Week 46th Wednesday
    November 8th 2016 Week 46th Tuesday
    windows 7文件共享方法
    Win7无线网络共享设置方法
    常量指针和指针常量
    如何查找局域网的外网ip
  • 原文地址:https://www.cnblogs.com/twodog/p/12140481.html
Copyright © 2011-2022 走看看