Android中的线程池

线程池的好处

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

Android中的线程池概念来源于Java中的Executor,Executor是一个接口,真正的线程池的实现为ThreadPoolExecutor。由于Android 中的线程池都是直接或是间接通过配置ThreadPoolExecutor来实现的,因此需要先介绍ThreadPoolExecutor。

ThreadPoolExecutor

ThreadPoolExecutor是线程池的真正实现,它的构造方法提供了一系列参数来配置线程池。下面是ThreadPoolExecutor的一个比较常用的构造方法

public ThreadPoolExecutor(int corePoolSize,
                        int maximunPoolSize,
                        long keepAliveTime,
                        TimeUnit unit,
                        BlockingQueue<Runnable> workQueue,
                        ThreadFactoty threadFactory)

corePoolSize

线程池的核心线程数,默认情况下,核心线程会在线程池中一直存活,即使它们处于闲置状态。如果将TheradPoolExecutor的allowCoreThreadTimeOut属性设置为true,那么闲置的核心线程在等待新任务到来时会有超时策略,这个时间间隔由keepAliveTime所指定,当等待时间超过keepAliveTime,核心线程就会被终止

maximunPoolSize

线程池所能容纳的最大线程数,当活动线程数达到这个数值时,后续的新任务就会被阻塞

keepAliveTime

非核心线程闲置的超时时长,超过这个时长,非核心线程就会被回收。当ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true时,同样会作用于核心线程

unit

用于指定keepAliveTime参数的时间单位,这是个枚举,常用的有MILLISECONDS(毫秒)、SECONDS(秒)以及MINUTES(分钟)等

workQueue

线程池中的任务队列,通过线程池的execute方法提交的Runnable对象会储存在这个参数中

threadFactory

线程工厂,为线程池提供创建新线程的功能。ThreadFactory是一个接口,它只有一个方法:Thread newThread(Runnable r)。

ThreadPoolExecutor执行任务时大致遵循如下规则:

  1. 如果线程池中的数量未到达核心线程的数量,那么会直接启用一个核心线程来执行任务
  2. 如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行
  3. 如果2步骤中无法将任务插到任务队列中,这往往是因为任务队列已满,这个时候如果线程数量未到达线程池规定的最大值,那么会立刻启动一个非核心线程来执行任务
  4. 如果步骤3中的线程数量已经达到线程池的最大容量,则拒绝执行这个任务,ThreadPoolExecutor会调用RejectedExecutionHandler的rejectedExecution方法来通知调用者’

ThreadPoolExecutor的参数配置在AsyncTask中有明显的体现,下面是AsyncTask中的线程池的配置情况:

    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
    // 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;

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

    /**
     * An {@link Executor} that can be used to execute tasks in parallel.
     */
    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;
    }

AsyncTask对THREAD_POOL_EXECUTOR这个线程池进行了配置,配置后的线程池的规格为:

  • 核心线程数最少为2个,最多为4个和CPU核心数-1的较少的那个
  • 线程池的最大线程数为CPU核心数的2倍+1
  • 核心线程有超时机制,线程在闲置时的超时时间为30秒
  • 任务队列的总量为128

线程池的分类

Android 中最常见的四类具有不同功能特性的线程池,它们都直接或间接的通过配置ThreadPoolExecutor来实现自己的功能特性,这四类线程池分别是:FixedThreadPool、CachedThreadPool、ScheduledThreadPool以及SingleThreadExecutor

1.FixedThreadPool

通过Executors的newFixedThreadPool方法来创建。它是一种线程数量固定的线程池,当线程处于空闲状态时,线程不会被回收,除非线程池关闭了。当所以线程都处于活动状态时,新任务都会处于等待状态,除非有线程空闲出来。由于FixedThreadPool只有核心线程并且这些核心线程不会被回收,意味着它能更快的响应外界的请求。

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads,nThreads,0L,TimeOut.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
}

2.CachedThreadPool

通过Executots的newCachedThreadPool方法创建。它是一种线程数量不定的线程池,只有非核心线程,并且最大线程数为Integer.MAX_VALUE。由于Integer.MAX_VALUE是很大的数,实际上就相当于最大线程数可以任意大。当线程池中的线程处于活动状态时,线程池会创建新的线程来处理新任务,否则利用空闲的线程处理新任务。这类线程池比较适合执行大量的耗时较少的任务。当整个线程池都处于闲置状态时,线程池中的线程都会因为超时而被停止,整个时候CachedThreadPool相当于没有任何线程,几乎不占用系统资源。

public static ExecutorService newCacheThreadPool() {
    return new ThreadPoolExecutor(0,Integer.MAX_VALUE,60L,TimeUnit.SECONDS,new SynchronousQueue<Runnable>());
}

3.ScheduledThreadPool

通过Executors的newScheduledThreadPool创建.它的核心线程数量固定,而非核心线程没有限制,而当非核心线程闲置时会被立即回收。这类线程池主要用于执行定时 任务和具有固定周期的重复任务

public static ScheduledExecutorService newScheduledThreadPool(int corePoolsize){
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize,Integer.MAX_VAUE,0,NANOSECONDS,new DelayedWorkQueue());
}

4.SingleThreadExecutor

通过Execuots的newSingleThreadExecutor方法来创建。这类线程池只有一个核心线程,它确保所有的任务都在同一个线程中按顺序进行。它的意义在于统一所有外界任务到一个任务中,使得这些任务之间不需要处理线程同步的问题

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1,1,0L,TimeUnit.MILLISECONDS,
        new LinkedBlockingQueue<Runnable>()));
}

下面代码演示了系统预置的4中线程池的典型使用方法

Runnable command = new Runnable () {
    @Override
    public void run() {
        SystemClock.sleep(2000);
    }
}

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
fixedThreadPool.execute(command);

ExecutorService cachedThreadPool = Executors.newCacheThreadPool();
cacheThreadPool.execute(command);

ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
//2000ms执行commend
scheduledThreadPools.schedule(command,2000,TimeUnit.MILLISECONDS)//延迟10ms后,每隔1000ms执行一次command
ScheduldedThreadPool.scheduleAtFixedRate(command,10,1000,TimeUnit.MILLISECONDS);

ExecutorService sigleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.executr(command);

注:本笔记来源于《Android开发艺术探索》相关知识

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值