在开发过程中经常会用到线程池,那么线程池有什么好吃呢?总结为一下三点:
- 重用线程池中的线程,避免因为线程池的创建和销毁所带来的性能开销。
- 能有效控制线程池的最大并发数,避免大量的线程之间因相互抢占系统资源而导致的阻塞现象。
- 能够对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。
Android中的线程池概念来源于java中的Executor,Executor是一个接口,在android中的具体实现是ThreadPoolExecutor,它提供了一系列参数来配置线程池,通过不同的参数可以创建不同的线程池,从线程池的功能特性上来说,Android线程池主要分为4类,这4类线程池可以通过Executors锁提供的工厂方法来得到。由于Android中的线程池都是直接或者间接通过配置ThreadPoolExecutor的方法来实现,因此介绍他们之前先介绍ThreadPoolExecutor、
ThreadPoolExecutor是线程池的真正实现,它的构造方法提供了一系列参数来配置线程池
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }
- corePooSize
线程池的核心线程数,默认情况下,核心线程数会在线程中一直存活,即使它们处于闲置状态。如果将ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,那么闲置的核心线程在等待新任务到来时会有超时策略,这个时间间隔由keepAliveTime所指定,当等待时间超过keepAliveTime所指定的时长后,核心线程就会被终止。
- maximumPoolSize
线程池所能容纳的最大线程数,当活动线程数达到这个数值后,后续的新任务将会被阻塞
- keepAliveTime
非核心线程闲置时的超时时长,超过这个时长,非核心线程就会被回收。当ThreadPoolExecutor的allowCoreTheadTimeOut属性设置为true时,keepAliveTime同样会作用域核心线程。
- unit
用于指定keepAliveTime参数的时间单位,这是一个枚举
- workQueue
线程池中的任务队列,通过线程池的execute方法提交的对象会存储在这个参数中。
- threadFactory
线程工厂,为线程池提供创建新线程的功能,ThreadFactory是一个接口,它只有一个方法:Thread newThread(Runnable r).
除了上述主要参数外,ThreadPoolThread还有一个不常用的参数RejectedExecutionHandler handler。当线程池无法执行新任务时,这可能是由于任务队列已满或者是无法成功执行任务,这个时候ThreadPoolExecutor会调用handler的rejectedExecution方法来通知调用者,默认情况下会直接抛出异常。
ThreadPoolExecutor执行任务时大致遵循以下规则:
- 如果线程池中的线程数量未达到核心线程的数量,那么会直接启动一个核心线程来执行任务。
- 如果线程池中线程数量已经达到或者超过核心线程数量,那么任务会被插入到任务对列中排队等待执行。
- 如果无法将任务插入到任务对列中,这往往是由于任务队列已满,这个时候如果线程数量未达到线程池规定的最大值,那么会立刻启动一个非核心线程来执行任务。
- 如果线程数量已经达到线程池规定的最大值,那么就拒绝执行此任务。
ThreadPoolExecutor的相关参数配置,在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);
从上面的代码来看,AsyncTask对Thread_POOL_EXECUTOR这个线程池进行了配置,规格如下
- 核心线程数等于CPU核心数 -1 ,最大为4,最小为2
- 最大核心数为CPU核心数 * 2 + 1
- 核心线程无超时机制,非核心线程在限制时的超时时间为30秒
- 任务队列容量为128
Android中最常见的四类具有不同功能特性的线程池,它们都直接或间接的通过配置ThreadPoolExecutor来实现自己的功能特性的,这4类线程池分别是FixedThreadPool、CachedThreadPool、ScheduleThreadPool、SingleThreadExecutor.
- FixedThreadPool
通过Executorsd的newFixedThreadPool方法来创建.它是一种线程数量固定的线程池,当线程处于空闲状态时,它们并不会被回收,除非线程池被关闭了。当所有的线程池都处于活动状态时,新任务都处于等待状态,直到有线程空闲出来。由于FixedThreadPool只有核心线程并且这些线程不会被回收,这就意味它能够更加快速的响应外界的请求。newFixedThreadPool方法的实现如下:
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
可以发现FixedThreadPool核心线程数和最大线程数相等,说明只有核心线程,并且这些核心线程没有超时机制,队列大小也没有大小限制。
- CachedThreadPool
通过Executors的newCachedThreadPool方法来创建。它是一种线程数量不定的线程池。它只有非核心线程,并且最大线程数量是Integer.MAX_VALUE。由于Integer.MAX_VALUE是一个很大的数,相当于没有限制。当线程池中的线程都处于活动状态时,线程池会创建新的线程来处理任务,否则就会利用空闲的线程来处理新任务。线程池中的空闲线程都有超时机制,这个超时时长是60s,超过这个时间闲置线程就会被回收。和FixedThreadPool不同的是,CacheThreadPool的任务队列其实相当于一个空集合,这将导致任何任务都会立即被执行,因为这种情况下SynchronousQueue是无法插入任务的。SynchronousQueue是一个非常特殊的队列,由于它在实际中比较少用,就不过多的探讨。从CacheThreadPool的特性来看,这类线程池比较适合执行大量的耗时较少的任务,当整个线程池都处于闲置状态时,线程池中的线程都会超时而被停止,这个时候CacheThreadPool之中实际上是没有任何线程的,几乎不占用系统资源。
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
- ScheduleThreadPool
通过Executors的newScheduledThreadPool方法来创建,他的核心线程数量是固定,而非核心线程数量是不固定的,并且当非核心线程闲置时会被立刻回收,ScheduledThreadPool这类线程池主要用于执行定时任务和具有固定周期的重复任务。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); }
public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS, new DelayedWorkQueue()); }
- SingleThreadPool
通过Executors的newSingleThreadPool方法创建,这类线程池内部只有一个核心线程,它确保所有的任务在同一个线程中按顺序执行,这使得这些任务之间不需要处理线程同步的问题。
*/ public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
除了上述的几种线程池外,可以根据实际需要可以灵活配置。下面是基本用法:
Runnable command = new Runnable() {
@Override
public void run() {
SystemClock.sleep(2000);
}
}ExecutorsService fixedThreadPool = Executors.newFixedThreadPool(4;
fixedThreadPool.execute(command);ExecutorsService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(command);ScheduledExecutorService scheduledThreradPool = Executors.newScheduledThreadPool(4);
///2000ms后执行
scheduledThreradPool.execute(command, 2000, TimeUnit.MILLISECONDS);
///延迟10ms后,没个1000ms执行一次command
scheduledThreradPool.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);ExecutorsService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(command);