提到线程池先说一下线程池的好处,相信读者都有所体会,线程池的优点可以概括为以下三点:
(1)重用线程池中的线程,避免因为线程创建和销毁带来的性能开销。
(2)能有效控制线程池的最大并发数,避免大量的县城之间互相抢占系统资源而导致的阻塞现象。
(3)能够对线程进行简单的管理,并提供定时执行以及指定间隔循环执行等功能。
Android 中的线程池的概念来源于 Java 中的 Executor,Executor 是一个接口,真正的线程池的实现为 ThreadPoolExecuto。ThreadPoolExecutor 提供了一系列参数来配置线程池,通过不同的参数可以创建不同的线程,从线程的功能上来说,.Android 的线程池主要分为四类,这四类线程池可以通过 Executors 所提供的工厂方式来得到,具体会在下面介绍。由于 Android 中的线程池都是直接或者间接通过配置 ThreadPoolExecutor 来实现的,因此及介绍它们之前先介绍下 ThreadPoolExecutor。
ThreadPoolExecutor
ThreadPoolExecutor 是线程池的真正实现,它的构造方法提供了一些列参数来配置线程池,下面介绍 ThreadPoolExecutor 的构造方法中各个参数的含义,这些参数将会直接影响到线程池的功能特性,下面是 ThreadPoolExecutor 一个比较常用的构造方法:
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters and default rejected execution handler.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}
corePoolSize
线程池的核心参数,默认情况下,核心线程会在线程池中一直存活,即便它们处于闲置状态。如果将 ThreadPoolExecutor 的 allowCoreThreadTimeOut 属性设置为 true,那么闲置的核心线程会在等待新任务到来时会有超市策略,这个时间间隔由 keepAliveTime 来指定,等待时间超过 keepAliveTime 所指定的时长后,核心线程会被终止。
maximumPoolSize
线程池所容纳的最大线程数,当活动线程数达到这个值以后,后续的新任务就会被阻塞
keepAliveTime
非核心线程闲置时的超时时长,超过这个时长,非核心线程就会被回收,当 ThreadPoolExecutor 的 allowCoreThreadTimeOut 属性设置为 true 时,keepAliveTime 同样作用于核心线程。
unit
用于指定 keepAliveTime 参数的时间单位,这是一个枚举,常用的有 TimeUnit.MILLSECONDS(毫秒),TimeUnit.SECONDS(秒)以及 TimeUnit.MINUTES(分钟)等。
workQueue
线程池的任务对咧,通过线程池的 execute 方法提交的 Runnable 对象会存储在这个参数中。
threadFactory
线程工厂,为线程池提供创建线程的功能。ThreadFactory 是一个接口,他只有一个方法 Thread newThread(Runnable r)。
除了上面的这些主要参数外,ThreadPoolExecutor 还有一个不同寻常的参数 RejectedExecutionHandler handler。当线程池无法执行新任务时,这可能是由于任务队列已满或者无法成功执行任务,这个时候 ThreadPoolExecutor 会调用 handler 的 rejectedExecution 方法来通知调用者,默认情况下 rejectedExecution 方法会直接跑出一个 RejectedExecutionException 异常,ThreadPoolExecutor 为 RejectedExecutionHandler 提供了几个可选值:AbortPolicy,DiscardPolicy,DiscardOldestPolicy 和 CallerRunsPolicy,其中 AbortPolicy 是默认值,它会直接跑出 RejectedExecutionException 异常,如下所示:
/**
* A handler for rejected tasks that throws a
* {@code RejectedExecutionException}.
*/
public static class AbortPolicy implements RejectedExecutionHandler {
/**
* Creates an {@code AbortPolicy}.
*/
public AbortPolicy() { }
/**
* Always throws RejectedExecutionException.
*
* @param r the runnable task requested to be executed
* @param e the executor attempting to execute this task
* @throws RejectedExecutionException always
*/
public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
ThreadPoolExecutor 执行任务时,大致遵循如下规则:
(1)如果线程池中的线程数量未达到核心线程数量,那么会直接启动一个核心线程来执行任务。
(2)如果线程池中的线程数量已经达到或者超过核心线程数量,那么任务会被插入到任务队列中派队等候执行。
(3)如果在步骤 2 中无法将任务插入到任务队列中,这旺旺是由于任务对咧已满,这个时候如果线程数量为达到线程池规定数量的最大值,那么会立即启动一个非核心线程来执行任务。
(4)如果步骤 3 中线程数量已经达到线程池的最大值,那么就拒绝执行任务,ThreadPoolExecutor 会调用 RejectedExecutionHandler 的 rejectedExecution 方法来通知调用者。
/**
* Executes the given task sometime in the future. The task
* may execute in a new thread or in an existing pooled thread.
*
* If the task cannot be submitted for execution, either because this
* executor has been shutdown or because its capacity has been reached,
* the task is handled by the current {@code RejectedExecutionHandler}.
*
* @param command the task to execute
* @throws RejectedExecutionException at discretion of
* {@code RejectedExecutionHandler}, if the task
* cannot be accepted for execution
* @throws NullPointerException if {@code command} is null
*/
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
/*
* Proceed in 3 steps:
*
* 1. If fewer than corePoolSize threads are running, try to
* start a new thread with the given command as its first
* task. The call to addWorker atomically checks runState and
* workerCount, and so prevents false alarms that would add
* threads when it shouldn't, by returning false.
*
* 2. If a task can be successfully queued, then we still need
* to double-check whether we should have added a thread
* (because existing ones died since last checking) or that
* the pool shut down since entry into this method. So we
* recheck state and if necessary roll back the enqueuing if
* stopped, or start a new thread if there are none.
*
* 3. If we cannot queue task, then we try to add a new
* thread. If it fails, we know we are shut down or saturated
* and so reject the task.
*/
int c = ctl.get();
if (workerCountOf(c) < corePoolSize) {
if (addWorker(command, true))
return;
c = ctl.get();
}
if (isRunning(c) && workQueue.offer(command)) {
int recheck = ctl.get();
if (! isRunning(recheck) && remove(command))
reject(command);
else if (workerCountOf(recheck) == 0)
addWorker(null, false);
}
else if (!addWorker(command, false))
reject(command);
}
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 这个线程池进行了配置,配置后的线程池规格如下:
(1)核心线程数量最小为2,最大4;
(2)线程池的最大线程数为 CPU 核心数的 2 倍 + 1;
(3)核心线程无超时机制,非核心线程在闲置时的超时时间为 30 秒;
(4)任务对咧的容量为 128。
————————————————我是分割线————————————————
线程池的分类
在上面我们已经对 ThreadPoolExecutor 的配置进行了详细的介绍,下面我们将接着介绍 Android 中最常见的四类具有不同功能特性的线程池,它们都直接或间接的通过配置 ThreadPoolExecutor 来实现自己的功能特性,这四类线程池分别是:FixedThreadPool、CachedThreadPool、ScheduledThreadPool 和 SingleThreadExecutor。
1.FixedThreadPool
通过 Executors 的 newFixedThreadPool 方法来创建。它是一种线程数量固定的线程池,当线程处于空闲状态时,它们并不会回收,除非线程关闭了。当所有的线程都处于活动状态时,新任务都会处于等待状态,知道有线程空闲出来。由于 FixedThreadPool 只有核心线程并且这些河西线程不会被回收,这就意味着它能够更加快速的响应外界的请求。newFixedThreadPool 方法实现如下,可以发现 FixedThreadPool 只有核心线程并且这些核心线程没有超时机制,另外任务队列也是没有大小限制的。
public static ExecutorService newFixedThreadPool(int nThreads) {
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 的任务对咧相当于一个空集合,这将导致任何任务都会被立即执行,因为这种场景下 SynchronousQueue 是无法插入新任务的。SynchronousQueue 是一个非常特殊的队列,在很多情况下可以把 SynchronousQueue 理解为一个无法存储元素的队列,由于它在实际中很少使用,这就不做深究了。从 CachedThreadPool 的特性来看,这类线程池比较适合执行大量的耗时较少的任务。当整个线程池都处于闲置状态时,线程池中的线程都会被超时而停止,这个时候 CachedThreadPool 之中实际上是没有任何线程的,它几乎不占用任何系统资源的。newCachedThreadPool 方法实现如下:
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
3.ScheduledThreadPool
通过 Executors 的 newScheduledThreadPool 方法来创建。它的核心线程数量是固定的,而非核心线程数量是没有限制的,并且当非核心线程闲置时会被立即回收。ScheduledThreadPool 这类线程池主要用于执行定时任务和具有固定周期的重复任务,ScheduledThreadPool 方法实现如下:
public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}
4.SingleThreadExecutor
通过 Executors 的 newSingleThreadExecutor 方法来创建,这类线程池内部只有一个核心线程,他确保所有的任务都在同一个线程中按顺序执行,SingleThreadExecutor 的意义在于统一所有的外接任务到一个线程中,这使得这些任务之间不需要处理线程同步的问题。newSingleThreadExecutor 方法的实现如下所示:
public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory));
}