mthoutai

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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); //能够自己定义 线程池     使用这两种方法

posted on 2017-05-23 17:27  mthoutai  阅读(187)  评论(0编辑  收藏  举报