一、线程池实例化的具体实现
此章节的内容,大部分集中在Executors类的源代码介绍上,各位有兴趣可以顺便看一下该类的源码。
1、newCachedThreadPool()和newFixedThreadPool(int nThreads),包括相应的重载方法(重载方法包含参数ThreadFactory)
把这两个方法放在一起,是因为这两个线程池都是直接通过实例化ThreadPoolExecutor类,只是传入的参数不同而已
CachedThreadPool:corePoolSize为0,maximumPoolSize为Integer.MAX_VALUE,BlockingQueue为SynchronousQueue<Runnable>实例;
FixedThreadPool:corePoolSize为nThreads,maximumPoolSize为nThreads,BlockingQueue为LinkedBlockingQueue<Runnable>实例;
由此可知:在初始化构造器的参数就可以推断出线程池大概的特性。
CachedThreadPool创建的线程数上限也只是Integer.MAX_VALUE,但实际应用中一般线程数不会超过这个值,所以就可以认定是“与所需数量相同的线程”。
FixedThreadPool由于corePoolSize与maximumPoolSize相同,一开始创建了数量为nThreads的线程,就不会再被回收,后续也不创建新的线程对象,LinkedBlockingQueue作为线程池的队列实例,超过nThreads后将线程任务添加到该列表,就表示后续添加的线程任务是按添加顺序执行的。
2、newSingleThreadExecutor()及重载方法
引入了静态内部类FinalizableDelegatedExecutorService,该类继承的父类DelegatedExecutorService,只是装饰了ExecutorService接口,里面的方法其实全部是由接口实例提供的实现。只是覆盖了finalize(),里面调用shutdown()方法(只是这个方法有修改)。
该静态内部类装饰的ThreadPoolExecutor实例参数如下:corePoolSize为1,maximumPoolSize为1,keepAliveTime为0,BlockingQueue为LinkedBlockingQueue<Runnable>实例;
3、newScheduledThreadPool() 及重载方法
直接返回ScheduledThreadPoolExecutor实例对象,只传入参数corePoolSize。
调用的父类构造器其实是ThreadPoolExecutor的构造器,默认的其他参数:maximumPoolSize为Integer.MAX_VALUE,keepAliveTime为0,BlockingQueue为DelayedWorkQueue实例;
4、newSingleThreadScheduledExecutor()及重载方法
引用了静态内部类DelegateScheduledExecutorService,装饰ScheduledExecutorService,corePoolSize为1。
以上几个是具有代表性的线程池的创建方式,由此可知,不同线程池的特性,很多情况下是由以上几个关键的参数来决定的,接下来的一个章节里,我们会深入地分析线程池的内部控制逻辑,深入地了解一下线程池是怎么样通过几个关键参数去体现它的特性。