Fighting.jpg
Android中的线程池的概率来源于Java中的Executor,然真正实现线程池的是ThreadPoolExecutor。接下来看下ThreadPoolExecutor的实例化。
/**
*
* @param corePoolSize 线程池的核心线程数
* @param maximumPoolSize 线程池锁容纳的最大线程数
* @param keepAliveTime 非核心线程闲置时的超时时长,超过这个时长非核心线程就会被回收。 当设置ThreadPoolExecutor的allowCoreThreadTimeOut属性
* 为true时,keepAliveTime同样会作用于核心线程
* @param unit 用于指定keepAliveTime参数的时间单位
* @param workQueue 线程池中的任务队列,通过线程池的execute方法提交的Runnable对象会存储在参数中
* @param threadFactory 线程工厂,为线程池提供创建新线程的功能。
* @param handler
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
ThreadPoolExcutor执行任务的时候会遵循以下规则:
- 线程池中的线程数量未达到核心线程的数量,会直接启动核心线程来执行任务
- 线程池中的线程数量已经达到或者超过核心线程的数量,这时候任务会被插入到任务队列中排队等待执行
- 如果在上一点中无法将任务插入到任务队列中,很大可能任务队列已满,这时候如果线程数量未达到线程池规定的最大值,那么会立刻启动一个非核心线程来执行任务
- 在如果上一点线程数量已经达到线程池规定的最大值,那么就拒绝执行此任务,ThreadPoolExecutor会调用RejectedExecutionHandler的rejectedExcution方法来通知调用者
那什么时候会出现上面所说的结果呢:</br>下面是AsyncTask对ThreadFactory的相关配置,摘录部分AsyncTask的源码
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "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());
}
};
//任务队列的容量为128
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;
}
以下省略N行
}
从上面标注可以看出,配置后的线程池规格:
- 核心线程数=CPU核心数+1
- 线程池的最大线程数=CPU核心数*2+1
- 核心线程无超机制,非核心线程在闲置时的超时时间为1s
- 任务队列的容量为128
Android中线程池分类
- FixedThreadPool
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
通过Executors的newFixedThreadPool方法来创建。
线程数量固定的线程池,线程处于空闲的时候并不会被回收,只有在线程池被关闭的时候才会。当所有的线程都处于活跃状态时,新任务都会处于等待状态,直到有线程空闲出来。</br>
==只有核心线程并且这些核心线程不会被回收,核心线程没有超时机制且任务队列没有大小限制,这样能够快速地响应外界的请求==
- CachedThreadPool
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- 线程不定的线程池,只有非核心线程数, 最大线程为Integer.MAX_VALUE。当线程池中的线程都处于活动状态时,线程池会创建新的线程来处理任务,否则利用空闲的新的任务。
- 线程池中的空闲线程都有超时机制,超时时长为60s,超过60s后闲置线程就会被回收。
==线程池中空闲线程都有超时机制, 适用于大量的耗时较少的任务==
- ScheduledThreadPool
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE,
DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,
new DelayedWorkQueue(), threadFactory);
}
- 核心线程数固定,非核心线程数没有限制,并且当非核心线程闲置时会被立即回收。
==执行定时和具有固定周期的重复任务==
- SingleThreadExecutor
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
内部只有一个核心线程,确保所有的任务都在同一线程中按照顺序执行
==统一外界任务到一个线程中,使得这些任务之间不需要处理线程同步问题==
使用线程池优点
- 重用线程池中的线程,避免因为线程的创造和销毁所带来的性能开销</br>
- 有效控制线程池的最大并发数,避免大量的线程之间因互相抢占系统资源而导致的阻塞问题
- 能够对线程进行简答的管理,并提供定时执行以及指定间隔循环执行等功能
后记
本文内容摘录《Android开发艺术探索》