线程池newFixedThreadPool

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
在这里插入图片描述

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值