Android线程池的开发精要

作者: ahking17 | 来源:发表于2017-02-14 18:16 被阅读191次
    使用线程池的好处

    可以归纳为3点:

    1. 重用线程池中的线程, 避免因为线程的创建和销毁所带来的性能开销.
    2. 有效控制线程池中的最大并发数,避免大量线程之间因为相互抢占系统资源而导致的阻塞现象.
    3. 能够对线程进行简单的管理,可提供定时执行和按照指定时间间隔循环执行等功能.

    线程池真正的实现类是ThreadPoolExecutor,它间接实现了Executor接口。
    ThreadPoolExecutor提供了一系列参数来配置线程池,通过不同的参数配置实现不同功能特性的线程池.
    Android为了方便开发者创建4种不同特性的ThreadPoolExecutor, 提供了一个Executors类,提供了4个静态工厂方法.
    eg. newFixedThreadPool().

    public class Executors {
    
        public static ExecutorService newFixedThreadPool(int nThreads) {
            return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
        }
    
    }
    
    ThreadPoolExecutor 构造方法的配置参数
    public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) {
    
    }
    
    
    corePoolSize: 线程池的核心线程数,默认情况下, 核心线程会在线程池中一直存活, 即使处于闲置状态. 
    但如果将allowCoreThreadTimeOut设置为true的话, 那么核心线程也会有超时机制, 在keepAliveTime设置的时间过后, 核心线程也会被终止.
    maximumPoolSize: 最大的线程数, 包括核心线程, 也包括非核心线程, 在线程数达到这个值后,新来的任务将会被阻塞.
    keepAliveTime: 超时的时间, 闲置的非核心线程超过这个时长,将会被销毁回收, 当allowCoreThreadTimeOut为true时,这个值也作用于核心线程.
    unit:超时时间的时间单位.
    workQueue:线程池的任务队列, 通过execute方法提交的runnable对象会存储在这个队列中.
    threadFactory: 线程工厂, 为线程池提供创建新线程的功能.
    handler: 任务无法执行时,回调handler的rejectedExecution方法来通知调用者.
    
    线程池的分类, 4个

    FixedThreadPool 固定大小线程池

    用法

    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(num);
    fixedThreadPool.execute(runnable对象);
    
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
    }
    

    特点:只有核心线程数,并且没有超时机制,因此核心线程即使闲置时,也不会被回收,因此能更快的响应外界的请求.

    使用场景: 需要快速响应外界请求.

    CachedThreadPool 只有非核心线程并且无限量的线程池

    用法:

    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    cachedThreadPool.execute(runnable对象);
    
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
    }
    

    特点:没有核心线程,非核心线程数量没有限制, 超时为60秒.
    使用场景: 适用于执行大量耗时较少的任务,当线程闲置超过60秒时就会被系统回收掉,当所有线程都被系统回收后,它几乎不占用任何系统资源.

    ScheduledThreadPool 执行定时任务的线程池

    ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(int corePoolSize);
    scheduledThreadPool.schedule(runnable对象, 2000, TimeUnit.MILLISECONDS);
    
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
              new DelayedWorkQueue());
    }
    
    

    特点:核心线程数是固定的,非核心线程数量没有限制, 没有超时机制.
    使用场景: 主要用于执行定时任务和具有固定周期的重复任务.

    SingleThreadExecutor 只有一个核心线程的线程池

    用法:

    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    singleThreadExecutor.execute(runnable对象);
    
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
    }
    

    特点:只有一个核心线程,并没有超时机制.
    使用场景: 意义在于统一所有的外界任务到一个线程中, 这使得在这些任务之间不需要处理线程同步的问题.

    AsyncTask的底层实现使用的就是ThreadPoolExecutor

    核心线程数为: 手机CPU数+1
    最大线程数为: 手机CPU数*2 +1
    任务队列BlockingQueue的容量为: 128

    public abstract class AsyncTask<Params, Progress, Result> {
        private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();//CPU数
        private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
        private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 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());
            }
        };
    
        private static final BlockingQueue<Runnable> sPoolWorkQueue =
                new LinkedBlockingQueue<Runnable>(128);
    
    //static的, 因此所有整个进程中, AsyncTask只有一个线程池.
        public static final Executor THREAD_POOL_EXECUTOR
                = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
                        TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory);
    }
    

    -----DONE.----------

    相关文章

      网友评论

        本文标题:Android线程池的开发精要

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