Android多线程(Executor线程池篇)

【齐天的博客】转载请注明出处(万分感谢!):
https://blog.csdn.net/qijinglai/article/details/80750088

关联文章:
Android多线程(Handler篇)
Android多线程(AsyncTask篇)
Android多线程(HandlerThread篇)
Android多线程(IntentService篇)

前言

Android多线程(AsyncTask篇)中提到可以通过自定义Executor来实现并行,这里涉及到线程池的概念。
Executor是Java中的概念,是一个接口,真正的线程池实现是ThreadPoolExecutor。它提供了一系列的参数来配置不同的线程池。按功能来分Android线程池主要分4类,均通过Executors提供的工厂方法得到。
由于Android的线程池都是直接或间接通过配置ThreadPoolExecutor得到的,所以先来看一下ThreadPoolExecutor。

ThreadPoolExecutor

ThreadPoolExecutor是线程池的真正实现,他的构造方法提供了一系列参数来配置线程池,下面先介绍一下其构造方法中的参数的含义。
这是一个很常用的构造方法:

public ThreadPoolExecutor(
            int corePoolSize,//核心线程数
            int maximumPoolSize,//最大线程数
            long keepAliveTime, //非核心线程的超时时间
            TimeUnit unit,//单位
            BlockingQueue<Runnable> workQueue,//任务队列 
            ThreadFactory threadFactory//线程工厂
            )
  • corePoolSize
    核心线程数,核心线程池默认会在线程池中一直存活,无论它是不是闲置。如果将ThreadPoolExecute的allowCoreThreadTimeOut设置为true,那么闲置的核心线程会执行超时策略,这个超时策略的时间间隔是由keepAliveTime所指定的。
  • maximumPoolSize
    线程池所能容纳的最大线程数,当活动的线程数达到这个数值后,后续的任务会被阻塞。
  • keepAliveTime
    非核心线程池的超时时长,非核心线程池闲置的时间超过这个时间就会被回收。当ThreadPoolExecute的allowCoreThreadTimeOut设置为true时,它同样也作用于核心线程。
  • unit
    用于指定keepAliveTime的单位。
  • workQueue
    线程池中的任务队列,通过线程池的execute方法提交的Runnable对象会储存在这个参数中。
  • threadFactory
    线程工厂,为线程池提供创建新线程的功能,ThreadFactory是一个接口,他只有一个方法:

    public interface ThreadFactory {
        Thread newThread(Runnable var1);
    }

    除了这些参数外还有个很不常用的参数RejectedExecutionHandler handler。当线程池无法执行新任务时(任务队列满了或者无法成功执行)会调用handler的rejectExecutionException。

执行规则

这里写图片描述

AsyncTask的线程池配置

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;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
            new LinkedBlockingQueue<Runnable>(128);
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());
        }
    };


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

在我的Android多线程(AsyncTask篇)这一篇中可以知道AsyncTask配置了THREAD_POOL_EXECUTOR这个线程池,由上面的代码可以知道此线程池的规格:

  • 核心线程数=((CPU核心数-1)和4比取小)后和2比取大
  • 最大线程数=2*CPU核心数+1
  • 核心线程无超时,非核心线程超时时间为30秒
  • 任务队列容量=128

线程池分类

这里介绍4中常见的线程池

  1. FixedThreadPool
    通过Executors.newFixedThreadPool创建
    ①只有核心线程且数量固定
    ②没有超时机制
    ③队列没大小限制

    /**
     * Creates a thread pool that reuses a fixed number of threads
     * operating off a shared unbounded queue.  At any point, at most
     * {@code nThreads} threads will be active processing tasks.
     * If additional tasks are submitted when all threads are active,
     * they will wait in the queue until a thread is available.
     * If any thread terminates due to a failure during execution
     * prior to shutdown, a new one will take its place if needed to
     * execute subsequent tasks.  The threads in the pool will exist
     * until it is explicitly {@link ExecutorService#shutdown shutdown}.
     *
     * @param nThreads the number of threads in the pool
     * @return the newly created thread pool
     * @throws IllegalArgumentException if {@code nThreads <= 0}
     */
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue<Runnable>());
    }
    
  2. CachedThreadPool
    通过Executors.newFixedThreadPool创建
    ①只有非核心线程,且数量不定。
    ②最大线程数Integer.MAX_VALUE,最多65535个线程
    ③超时时间60s
    他会立即执行任何任务,适用于大量耗时较少的操作

    /**
     * Creates a thread pool that creates new threads as needed, but
     * will reuse previously constructed threads when they are
     * available.  These pools will typically improve the performance
     * of programs that execute many short-lived asynchronous tasks.
     * Calls to {@code execute} will reuse previously constructed
     * threads if available. If no existing thread is available, a new
     * thread will be created and added to the pool. Threads that have
     * not been used for sixty seconds are terminated and removed from
     * the cache. Thus, a pool that remains idle for long enough will
     * not consume any resources. Note that pools with similar
     * properties but different details (for example, timeout parameters)
     * may be created using {@link ThreadPoolExecutor} constructors.
     *
     * @return the newly created thread pool
     */
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue<Runnable>());
    }
    
  3. ScheduledThreadPool
    通过Executors.newScheduledThreadPool来创建
    ①核心线程数固定
    ②非核心线程没限制
    ③非核心线程闲置时立即回收
    用于执行定时任务和有固定周期的任务

    /**
     * Creates a thread pool that can schedule commands to run after a
     * given delay, or to execute periodically.
     * @param corePoolSize the number of threads to keep in the pool,
     * even if they are idle
     * @return a newly created scheduled thread pool
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
  4. SingleThreadExecutor
    通过Executors.newSingleThreadExecutor来创建
    ①一个核心线程
    同意外界任务进来按顺序执行

    /**
     * Creates an Executor that uses a single worker thread operating
     * off an unbounded queue. (Note however that if this single
     * thread terminates due to a failure during execution prior to
     * shutdown, a new one will take its place if needed to execute
     * subsequent tasks.)  Tasks are guaranteed to execute
     * sequentially, and no more than one task will be active at any
     * given time. Unlike the otherwise equivalent
     * {@code newFixedThreadPool(1)} the returned executor is
     * guaranteed not to be reconfigurable to use additional threads.
     *
     * @return the newly created single-threaded Executor
     */
    public static ExecutorService newSingleThreadExecutor() {
        return new FinalizableDelegatedExecutorService
            (new ThreadPoolExecutor(1, 1,
                                    0L, TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>()));
    }

线程池的好处

除了前面介绍的配置好的线程池之外,我们也可以根据需求自己配置线程池,就写到这吧,最后总结下线程池的好处。

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

本文参考《Android开发艺术探索》第十一章内容

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Qi T

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值