一,写在前面
线程池的好处:可以在设定固定数量的线程池,并重用线程池中的线程,避免了线程不断的创建和销毁带来的性能开销。另外,还可以定时以及间隔循环执行任务。
Android线程池有哪些:FixedThreadPool,SingleThreadPool,CacheThreadPool,ScheduledThreadPool。事实上,前面列出的四种线程池并不是类,是对线程池的描述。具体来说,FixedThreadPool是固定大小线程池,SingleThreadPool是单任务线程池,CacheThreadPool非固定大小线程池,ScheduledThreadPool是具有定时,间隔循环执行任务的线程池。
什么是线程池?Android线程池是由Java提供的原生API支持,代表线程池的是一个接口Executor,它只有一个execute方法。有一些子类:ThreadPoolExecutor,AbstractExecutorService;有一些子接口:ScheduledExecutorService,ExecutorService。
接口Executor真正实现类是ThreadPoolExecutor,上面提到的四种线程池实质都是ThreadPoolExecutor,只是创建ThreadPoolExecutor对象时传入的参数值不同。因此,研究常用四种线程池前需要认识ThreadPoolExecutor,下面会重点研究。
二,ThreadPoolExecutor分析
查看接口Executor源码:
public interface Executor {
/**
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread, at the discretion of the {@code Executor} implementation.
*
* @param command the runnable task
* @throws RejectedExecutionException if this task cannot be
* accepted for execution
* @throws NullPointerException if command is null
*/
void execute(Runnable command);
}
第13行,定义了一个execute方法,子类ThreadPoolExecutor会重写该方法,参数command指被执行的任务。
查看ThreadPoolExecutor构造方法,主要研究其参数,源码如下:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler){
//...code
}
corePoolSize:核心线程的数量。核心线程在默认情况下,没有闲置状态的超时机制,不会被系统回收。如果调用ThreadPoolExecutor$allowCoreThreadTimeOut(true),设置属性allowCoreThreadTimeOut值为true,那么核心线程在闲置状态时有超时机制,可以被回收。
maximumPoolSize:线程池中允许的线程最大数量;