我们的任务队列和其正开始看起来像:为什么总是threadPoolExecutor.getActiveCount()<= maximumPoolSize/2?
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(maximumPoolSize, maximumPoolSize, 50000L, TimeUnit.MILLISECONDS, queue);
的maximumPoolSize
值是200工作时的队列中获得了大量的线程(上千),但threadPoolExecutor.getActiveCount()
返回的值总是小于或等于100。例如,值threadPoolExecutor.getActiveCount()
和queue.size()
被记录如下:
logger.debug("Active threads: " + threadPoolExecutor.getActiveCount() + ". The queue has " + queue.size() + " threads.");
并且作为结果,我们得到以下日志:
Active threads: 1. The queue has 0 threads.
Active threads: 2. The queue has 0 threads.
Active threads: 3. The queue has 0 threads.
Active threads: 4. The queue has 0 threads.
Active threads: 5. The queue has 0 threads.
...
Active threads: 86. The queue has 0 threads.
Active threads: 87. The queue has 1 threads.
Active threads: 88. The queue has 1 threads.
Active threads: 89. The queue has 1 threads.
Active threads: 90. The queue has 1 threads.
...
Active threads: 99. The queue has 1 threads.
Active threads: 100. The queue has 1 threads.
Active threads: 100. The queue has 2 threads.
Active threads: 100. The queue has 3 threads.
Active threads: 100. The queue has 4 threads.
...
Active threads: 100. The queue has 1874 threads.
Active threads: 100. The queue has 1875 threads.
Active threads: 100. The queue has 1876 threads.
Active threads: 100. The queue has 1877 threads.
Active threads: 100. The queue has 1878 threads.
Active threads: 100. The queue has 1879 threads.
Active threads: 100. The queue has 1880 threads.
Active threads: 100. The queue has 1881 threads.
Active threads: 100. The queue has 1882 threads.
Active threads: 100. The queue has 1883 threads.
个
的文档说threadPoolExecutor.getActiveCount()
方法
返回正在积极执行 任务
但是线程的大致数量,为什么总是这样一个近似值maximumPoolSize
/2的最大阈值?它应该是这样吗?
P.S.我无法重现这种情况:在我的PC上,在这种情况下总是有200个活动线程。但上述日志不是来自我的电脑。它可以取决于处理器/虚拟内核的数量吗?
我也发现有趣的一段代码在The Grey Blog:
int cpus = Runtime.getRuntime().availableProcessors();
int maxThreads = cpus * scaleFactor;
maxThreads = (maxThreads > 0 ? maxThreads : 1);
但最终我很困惑,因为Runtime.getRuntime().availableProcessors()
值为8我的电脑上。
注意:除非你有这么多的逻辑CPU,你可能会发现,拥有更多线程比较慢,但它看起来像你的最高设置为100 @VickyThakor建议。 –
@PeterLawrey,我编辑了我的帖子 – Ksenia
我建议你打印'threadPoolExecutor.getPoolSize()'最大值不取决于你拥有的核心数量,只有在这点上有更多的不是一个好主意。 –