Android线程池详解
前言
在开发中经常会使用到线程来进行异步操作,但是每个线程的创建和销毁都需要一定的开销。所以就需要线程池来对线程进行管理。Android中的线程池来源于Java中的Executor,Executor是一个接口,真正线程池实现类是ThreadPoolExecutor。
ThreadPoolExecutor
我们可以通过ThreadPoolExecutor来创建一个线程池,ThreadPoolExecutor有4个构造方法,它们提供了一系列参数来配置线程池。下面是ThreadPoolExecutor的一个参数最多的构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
下边解释一下各个参数:
---------int corePoolSize
核心线程数。默认情况下线程池是空的,只有任务提交时才会创建线程。如果当前运行的线程数少于corePoolSize,则创建新线程来处理任务