java 动态线程池_java线程池参数动态化方案

前言:本文章参考美团的线程池动态参数配置。测试有效

解析:jdk提供了一套下线程池参数动态化的api

分为两部分

1.阻塞队列的修改

2.其他参数的修改

第一部分

public class ThreadPoolChangeDemo {

public static void main(String[] args) throws InterruptedException {

dynamicThreadPool();

}

public static ThreadPoolExecutor buildThreadPool(){

return new ThreadPoolExecutor(2,

50,

60,

TimeUnit.SECONDS,

new LinkedBlockingQueue<>(50),

new ThreadFactory() {

@Override

public Thread newThread(Runnable r) {

return new Thread();

}

});

}

private static void dynamicThreadPool() throws InterruptedException {

ThreadPoolExecutor threadPoolExecutor = buildThreadPool();

for (int i = 0; i < 15; i++) {

threadPoolExecutor.submit(()->{

printPoolSize(threadPoolExecutor,"创建线程池!!!!");

try {

TimeUnit.SECONDS.sleep(5000);

} catch (InterruptedException e) {

e.printStackTrace();

}

});

}

printPoolSize(threadPoolExecutor,"改变之前");

TimeUnit.SECONDS.sleep(1);

threadPoolExecutor.setMaximumPoolSize(100);

threadPoolExecutor.setCorePoolSize(50);

threadPoolExecutor.prestartAllCoreThreads();

//        Resize linkedBlockingQueue = (LinkedBlockingQueue) threadPoolExecutor.getQueue();

printPoolSize(threadPoolExecutor,"改变之后");

}

private static void printPoolSize(ThreadPoolExecutor pool,String name){

LinkedBlockingQueue linkedBlockingQueue = (LinkedBlockingQueue) pool.getQueue();

System.out.println(name);

System.out.println("最大线程数:"+pool.getMaximumPoolSize());

System.out.println("核心线程数:"+pool.getCorePoolSize());

System.out.println("线程池活跃度:"+(pool.getActiveCount()/pool.getMaximumPoolSize()));

System.out.println("队列大小:"+linkedBlockingQueue.size());

System.out.println("队列剩余大小:"+linkedBlockingQueue.remainingCapacity());

}

}

第二部分

思路: LinkedBlockingQueue 粘贴一份出来,修改个自定义的队列名字,然后把 Capacity 参数的 final 修饰符去掉,并提供其对应的 get/set 方法。

07f13894438f168d017d332fd97af399.png

然后在程序里面把原来的队列换掉:

2e397a9cb4cdde82d3abe78e63eda44c.png

运行起来看看效果:

6b2bc1c1f662bcfebf8800c9881c6edc.png

可以看到,队列大小确实从 10 变成了 100,队列使用度从 100% 降到了 9%

这个过程中涉及到的面试题有哪些?

问题一:线程池被创建后里面有线程吗?如果没有的话,你知道有什么方法对线程池进行预热吗?

线程池被创建后如果没有任务过来,里面是不会有线程的。如果需要预热的话可以调用下面的两个方法:

全部启动:

99af7ebe3dfe0a6d8071ca59813f755e.png

仅启动一个:

9e6ef4f04106209ab745aeaaa59c8855.png

问题二:核心线程数会被回收吗?需要什么设置?

核心线程数默认是不会被回收的,如果需要回收核心线程数,需要调用下面的方法:

ef7d6c676848450ab82da30110ce9f17.png

allowCoreThreadTimeOut 该值默认为 false。

dc2f838d99b64dac63ddad88bd8a14bb.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值