1.查看newFixedThreadPool线程池创建方法
使用newFixedThreadPool创建线程池
Executor cachedThread1 = Executors.newFixedThreadPool(2);
查看实现方式
ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>());
从源码可以看出初始核心数和最大核心数是一样的值,keepAliveTime是0
使用的队列是LinkedBlockingQueue,并且没设置队列的大小,从new LinkedBlockingQueue的源码看:
public LinkedBlockingQueue() { this(Integer.MAX_VALUE); }
可以看出没设置大小,则为Integer.MAX_VALUE
2.模拟newFixedThreadPool
int corePoolSize = 2;
int maximumPoolSize = 2;
long keepAliveTime = 60L;
LinkedBlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>();
Executor cachedThread = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS,
workQueue);
for (int i = 0; i < 1000; i++) {
System.out.println("=====" + i);//设置i==3的时候或20的时候断点生效
cachedThread.execute(new Runnable() {
@Override
public void run() {
try {
//此处等待10秒,用于观察各参数值的变化
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("threadName:" + Thread.currentThread().getName());
}
});
}
3.运行程序参数结果:
4.总结
newFixedThreadPool采用队列缓存线程的模式,但是队列中没有设置最大值默认是int的最大值,这样会导致内存问题。
5.延伸newSingleThreadExecutor
从源码来看newSingleThreadExecutor是一个特殊的newFixedThreadPool