我們的任務隊列和其正開始看起來像:爲什麼總是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()'最大值不取決於你擁有的核心數量,只有在這點上有更多的不是一個好主意。 –