Android进阶知识(二十四):Android的线程池
相比于线程,线程池有三点优点:
① 重用线程池中的线程,避免因为线程的创建和销毁所带来的性能开销。
② 能有效控制线程池的最大并发数,避免大量的线程之间因互相抢占系统资源而导致的阻塞现象。
③ 能够对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。
Android中的线程池真正实现是ThreadPoolExecutor,其提供一系列参数配置线程池。从功能特性上,Android的线程池有4类,以下进行介绍。
一、ThreadPoolExecutor
ThreadPoolExecutor是线程池的真正实现,其构造方法提供了一系列参数来配置线程池,这些参数直接影响线程池的功能特性。
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory)
这些参数的含义如下表所示。
参数 | 含义 |
corePoolSize | 线程池的核心线程数,默认情况下,核心线程会在线程池一直存活,即使它们处于闲置状态。 |
maximumPoolSize | 线程池所能容纳的最大线程数,当活动线程数达到这个数值后,后续任务将会阻塞。 |
keepAliveTime | 非核心线程闲置时的超时时长,超过时长,非核心线程会被回收。当allowCoreThreadTimeOut属性设置为true时,keepAliveTime同样作用于核心线程。 |
unit | 指定keepAliveTime参数的时间单位,常用的有TimeUnit.MILLISECONDS等 |
workQueue | 线程池中的任务队列,通过线程池的execute方法提交的Runnable对象会存储在这个参数中。 |
threadFactory | 线程工厂,为线程池提供创建新线程的功能。 |
RejectedExecutionHandler handler | 不常用参数,当线程池无法执行新任务时(任务队列已满或无法成功执行任务),调用hadler的rejectedExecution方法通知调用者。 |
ThreadPoolExecutor执行任务时大致遵循如下规则:
① 如果线程池中的线程数量未达到核心线程的数量,那么会直接启动一个核心线程来执行任务。
② 如果线程池中线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行。
③ 如果在步骤2中无法将任务插入到任务队列中,往往是队列已满,这时如果线程数量未达到线程池规定的最大值,那么会立刻启动一个非核心线程来执行任务。
④ 如果步骤3中线程数量已经达到线程池固定的最大值,那么拒绝执行此任务,调用RejectedExecutionHandler的rejectedExecution方法来通知调用者。
二、线程池的分类
Android中最常见的四类具有不同功能特性的线程池,它们都直接或者间接地通过配置ThreadPoolExecutor来实现。四类线程池分别为FixedThreadPool、CachedThreadPool、ScheduledThreadPool以及SingleThreadExecutor。
- FixedThreadPool
通过Executors的newFixedThreadPool方法创建,源码如下,该线程池只有核心线程并且没有超时限制,另外任务队列没有大小限制。
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
从中可以得到该线程池的功能特性如下。
线程池 | 功能特性 |
FixedThreadPool | 线程数量固定 |
只有核心线程并且核心线程不会被回收,除非线程池被关闭,这意味着它能够更快地响应外界的请求 | |
任务队列没有大小限制 | |
当所有线程都处于活动状态,新任务都会处于等待状态,直到有线程空闲出来 |
- CachedThreadPool
通过Executors的newCachedThreadPool方法来创建,源码如下。
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
从中可以得到该线程池的功能特性如下。
线程池 | 功能特性 |
CachedThreadPool | 线程数量不定 |
只有非核心线程,并且其最大线程数为Interger.MAX_VALUE(任意大) | |
空闲线程都有超时机制,超时时长为60s,超时线程会被回收 | |
当所有线程都处于活动状态,线程池会创建新的线程来处理新任务,否则利用空闲的线程处理 | |
任务队列相当于空集合,这导致任何任务都会立即执行 |
- ScheduledThreadPool
通过Executors的newScheduledThreadPool方法创建,源码如下。
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());
}
从中可以看出该线程池的功能特性如下。
线程池 | 功能特性 |
ScheduledThreadPool | 核心线程数量固定,非核心线程数没有限制 |
当非核心线程闲置时,立即被回收 | |
主要用于执行定时任务和具有固定周期的重复任务 |
- SingleThreadExecutor
通过Executors的newSingleThreadExecutor方法创建,源码如下。
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
从中可以看出该线程池的功能特性如下。
线程池 | 功能特性 |
SingleThreadExecutor | 只有一个核心线程,它确保所有的任务都在同一个线程中按顺序执行 |
统一所有的外界任务到一个线程中,使得这些任务之间不需要处理线程同步的问题 |
这四种线程池的典型用法示例代码如下所示。
Runnable command = new Runnable() {
@Override
public void run() {
SystemClock.sleep(2000);
}
};
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);
fixedThreadPool.execute(command);
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool.execute(command);
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(4);
// 2000ms后执行command
scheduledThreadPool.schedule(command, 2000, TimeUnit.MILLISECONDS);
// 延迟10ms后,每隔1000ms执行一次command
scheduledThreadPool.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(command);
参考资料:《Android开发艺术探索》