为什么要用线程池呢?当然是有好处的啊:
- 线程可以重用,节省开销,优化性能。
- 可以控制最大并发数,避免大量线程因为互相抢占系统资源而导致的阻塞现象。
- 能够对线程进行简单的管理,提供定时执行以及指定间隔循环等功能。
Android中的线程池来自于Executor,但是Executor是一个接口,真正的线程池的实现为ThreadPoolExecutor,Android 中的常见的线程池FixThreadPool、CachedThreadPool 、ScheduledThreadPool以及SingleThreadExecutor都是直接或间接的通过配置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
线程池核心线程数,默认核心线程会一直存活,如果allowCoreThreadTimeOut设置为true,那么当等待keepAliveTime所指定的时长后,核心线程就会被终止。
maximumPoolSize
线程池所能容纳的最大线程数
keepAliveTime
非核心线程闲置的最大超时时长,如果allowCoreThreadTimeOut设置为true时,同样会作用于核心线程。
unit
指定keepAliveTime的时间单位
workQueue
线程池的任务队列,通过execute提交的线程会存储在这个参数中。
threadFactory
线程工厂,用于创建一个新的线程。
FixThreadPool
/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
看注释,是一种固定数量的线程池,当所有的线程都处于活动状态时,新的任务都会处于等待状态,直到有线程空闲出来。它没有超时机制,任务队列也没有大小限制,但是可以快速响应请求。
CachedThreadPool
/**
* Creates a thread pool that creates new threads as needed, but
* will reuse previously constructed threads when they are
* available. These pools will typically improve the performance
* of programs that execute many short-lived asynchronous tasks.
* Calls to {@code execute} will reuse previously constructed
* threads if available. If no existing thread is available, a new
* thread will be created and added to the pool. Threads that have
* not been used for sixty seconds are terminated and removed from
* the cache. Thus, a pool that remains idle for long enough will
* not consume any resources. Note that pools with similar
* properties but different details (for example, timeout parameters)
* may be created using {@link ThreadPoolExecutor} constructors.
*
* @return the newly created thread pool
*/
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}```
只有非核心线程,并且线程数量不固定,最大线程数为Integer.MAX_VALUE,当所有线程为激活状态时,会创建一个新的线程,否则就会利用空闲的线程来执行任务。比较适合大量耗时少的任务。
####ScheduledThreadPool
```/**
* Creates a thread pool that can schedule commands to run after a
* given delay, or to execute periodically.
* @param corePoolSize the number of threads to keep in the pool,
* even if they are idle
* @return a newly created scheduled thread pool
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}```
核心线程固定,非核心线程没有固定,当非核心线程闲置时立即回收。这类线程池重要用于定时任务和具有周期的重复任务。
####SingleThreadExecutor
/**
* Creates a single-threaded executor that can schedule commands
* to run after a given delay, or to execute periodically.
* (Note however that if this single
* thread terminates due to a failure during execution prior to
* shutdown, a new one will take its place if needed to execute
* subsequent tasks.) Tasks are guaranteed to execute
* sequentially, and no more than one task will be active at any
* given time. Unlike the otherwise equivalent
* {@code newScheduledThreadPool(1)} the returned executor is
* guaranteed not to be reconfigurable to use additional threads.
* @return the newly created scheduled executor
*/
public static ScheduledExecutorService newSingleThreadScheduledExecutor() {
return new DelegatedScheduledExecutorService
(new ScheduledThreadPoolExecutor(1));
}
只有一个核心线程,确保所有的任务都在同一个线程里顺序执行。统一外部任务到一个线程之中,使得任务之间不再需要处理线程同步的问题。