Android中的线程池
提到线程池就必须说一下线程池的好处,线程池的优点可以概括为以下三点:
(1)重用线程池中的线程,避免因为线程的创建和销毁所带来的性能开销。
(2)能有效控制线程池的最大并发数,避免大量的线程之间因互相抢占系统资源而导致的阻塞现象。
(3)能够对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。
Android中的线程池的概念来源于java中的Executor,Executor是一个接口,真正的线程池的实现为ThreadPoolExecutor。
ThreadPoolExecutor提供了一系列参数来配置线程池,通过不同的参数可以创建不同的线程池,从线程池的功能特性上来说,
Android的线程池主要分为4类,这4类线程池可以通过Executors所提供的工厂方法来得到。由于Android中的线程池都是直接
或者间接通过配置ThreadPoolExecutor来实现的,下面先来看看ThreadPoolExecutor。
ThreadPoolExecutor
ThreadPoolExecutor 是线程池的真正实现,它的构造方法提供了一系列参数来配置线程池,下面介绍ThreadPoolExecutor 的
构造方法中各个参数的含义,这些参数将会直接影响到线程池的功能特性,下面是ThreadPoolExecutor的一个比较常用的构造
方法。
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory)
corePoolSize:
线程池的核心线程数,默认情况下,核心线程会在线程池中一直存活,即使它们处于闲置状态。如果将ThreadPoolExecutor的
allowCoreThreadTimeOut 属性设置为 true,那么闲置的核心线程在等待新任务到来时会有超时策略,这个时间间隔由
keepAliveTime所指定,当等待时间超过keepAliveTime 所指定的时长后,核心线程就会被终止。
maximumPoolSize:
线程池所能容纳的最大线程数,当活动线程数达到这个数值后,后续的新任务将会被阻塞。
keepAliveTime:
非核心线程闲置时的超时时长,超过这个时长,非核心线程就会被回收。当ThreadPoolExecutor 的 allowCoreThreadTimeOut
属性设置为 true 时,keepAliveTime 同样会作用于核心线程。
unit:
用于指定 keepAliveTime 参数的时间单位,这是一个枚举,常用的有 TimeUnit.MILLISECONDS(毫秒),
TimeUnit.SECONDS(秒) 以及 TimeUnit.MINUTES (分钟)等。
workQueue:
线程池中的任务队列,通过线程池的 execute 方法提交的 Runnable 对象会存储在这个参数中。
threadFactory:
线程工厂,为线程池提供创建新线程的功能。ThreadFactory是一个接口,它只有一个方法:Thread newThread(Runnable r)
ThreadPoolExecutor 执行任务时大致遵循如下规则:
1. 如果线程池中的线程数量未达到核心线程的数量,那么会直接启动一个核心线程来执行任务。
2. 如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入带任务队列中排队等待执行。
3. 如果在步骤2中无法将任务插入到任务队列中,这往往是由于任务队列已满,这个时候如果线程数量未达到线程池规定的最大
值,那么会立刻启动一个非核心线程来执行任务。
4. 如果在步骤3 中线程数量已经达到线程池规定的最大值,那么就拒绝执行此任务,ThreadPoolExecutor 会调用
RejectedExecutionHandler 的 rejectedExecution 方法来通知 调用者。
Android常见的四类具有不同功能特性的线程池:
它们都直接或间接地通过配置 ThreadPoolExecutor 来实现自己的功能特性,
这四类线程池分别是 FixedThreadPool,CachedThreadPool, ScheduledThreadPoolExecutor 以及 SingleThreadExecutor。
1. FixedThreadPool:
通过Executors的newFixedThreadPoolExecutor 方法来创建。它是一种线程数量固定的线程池,当线程处于空闲状态时,
它们并不会被回收,除非线程池被关闭了。当所有的线程都处于活动状态时,新任务都会处于 等待状态,直到有线程空闲
出来。由于 FixedThreadPool 只有 核心线程并且这些核心线程不会被回收,这意味着它能够更加快速地响应外界的请求。
public static ExecutorService newFixedThreadPool(int nThreads)public{
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
2. CachedThreadPool
通过 Executors 的 newCachedThreadPool 方法来创建。它是一种线程数量不定的线程池,它只有非核心线程,并且其最大
线程数为 Integer.MAX_VALUE。由于Integer.MAX_VALUE是一个很大的数,实际就相当于最大线程数可以任意大。当线程池
中的线程都处于活动状态时,线程池会创建新的线程来处理新任务,否则就会利用空闲的线程来处理新任务。线程池中的空闲线
程都有超时机制,时长为 60秒,超过60秒 闲置线程就会被回收。和FixedThreadPool 不同的是,CachedThreadPool 的任务
队列其实相当于一个空集合,这将导致任何任务都会立即被执行。从CachedThreadPool 的特性来看,这类线程池比较适合
执行大量的耗时较少的任务。当整个线程池都处于闲置状态时,线程池中的线程都会超时而停止,这个时候CachedThreadPool
之中实际上是没有任何线程的,它几乎是不占用任何系统资源。
public static ExecutorService newCachedThreadPool(){
return new ThreadPoolExecutor(0, Integer.MAX_VAULE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
3. ScheduledThreadPool
通过Executors 的 newScheduledThreadPool 方法来创建。它的核心线程数量是固定的,而非核心线程数是没有限制的,
并且当核心线程闲置时会立刻被回收。ScheduledThreadPool 这类线程主要用于执行定时任务和具有固定周期的重复任务。
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize){
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize){
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSEONDS,
new DelayedWorkQueue());
}
4. SingleThreadExecutor
通过Executors 的 newSingleThreadExecutor 方法来创建。这类线程池内部只有一个核心线程,它确保所有的任务都在
同一个线程中按顺序执行。SingleThreadExecutor 的意义在于 统一所有的外界任务到 一个线程中,这使得在这些 任务之间
不需要处理线程同步的问题。
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);
}
};
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执行一次
scheduledThreadPool.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
singleThreadExecutor.execute(command);