gpt4 book ai didi

java - java中ThreadPoolExecutor maximumPoolSize的作用是什么

转载 作者:行者123 更新时间:2023-11-30 06:42:12 24 4
gpt4 key购买 nike

我正在为一些非常简单的事情而苦苦挣扎......

我的真实项目多年来一直受到未知问题的困扰,他们决定创建一个非常简单的测试,结果让我感到害怕......

这是测试:

ExecutorService t = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(600));
for (int i = 0; i < 100; i++) {
final int i1 = i;
t.execute(new Runnable() {

@Override
public void run() {
while (true) {
System.out.println(i1);
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}

}
});
}

我正在创建一个线程池,其中包含 10 个核心线程和 20 个 maximumPoolSize然后我给它 100 个线程,每个线程将简单地打印一个固定数字...

我谦虚愚蠢的想法是:

The pool has 10 threads, will print 0-9 randomly then after some instans 10 extra threads will be created and pool will print from 0-19 randomly

这对我来说很明显,因为 maxSize 是 20,在最坏的情况下它应该接受 20 个任务......

但结果是0-9一直打印

问题是:如果永远不会安排额外的线程执行,maximumPoolSize 的意义何在?

最佳答案

正如@Oleg 正确指出的那样,池工作正常,但有一个我不知道的实现细节。

只有当任务队列已满时才会创建额外的线程

这篇文章解释得更好: http://www.bigsoft.co.uk/blog/2009/11/27/rules-of-a-threadpoolexecutor-pool-size

Take this example. Starting thread pool size is 1, core pool size is 5, max pool size is 10 and the queue is 100.

Sun's way: as requests come in threads will be created up to 5, then tasks will be added to the queue until it reaches 100. When the queue is full new threads will be created up to maxPoolSize. Once all the threads are in use and the queue is full tasks will be rejected. As the queue reduces so does the number of active threads.

User anticipated way: as requests come in threads will be created up to 10, then tasks will be added to the queue until it reaches 100 at which point they are rejected. The number of threads will rename at max until the queue is empty. When the queue is empty the threads will die off until there are corePoolSize left.

所以 Java 会等到队列爆满前的最后一秒来创建新线程...

关于java - java中ThreadPoolExecutor maximumPoolSize的作用是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53919084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com