2012-07-23 47 views
0

我爲工作線程使用了FixedThreadPool。以下是我創造了它:Java FixedThreadPool不適用於設置池大小?

ThreadPoolExecutor producerThreadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(25); 

所以我把它的大小爲25,我想應該只有最多25個活動線程,在任何時候? (如我錯了請糾正我)。

然後,我的主線程不斷嘗試同時提交30個工作線程,如果有線程池中的空閒線程:

if(producerThreadPool.getActiveCount() <= 25) 

但是當我調試它,我得到這個日誌:

Mon Jul 23 14:04:42 EDT 2012: {"queued_count":"0","active_count":"28","scheduled_tasks":"28","core_pool_size":"1000","pool_size":"29"} 
Mon Jul 23 14:04:43 EDT 2012: {"queued_count":"0","active_count":"3","scheduled_tasks":"33","core_pool_size":"1000","pool_size":"34"} 
Mon Jul 23 14:04:44 EDT 2012: {"queued_count":"0","active_count":"0","scheduled_tasks":"60","core_pool_size":"1000","pool_size":"60"} 
Mon Jul 23 14:04:45 EDT 2012: {"queued_count":"0","active_count":"0","scheduled_tasks":"90","core_pool_size":"1000","pool_size":"90"} 
... 

隊列總是空的,core_pool_size仍然是1000,並且pool_size一直增加到1000,但是我認爲core_pool_size應該是25,並且應該有排隊的任務?

我做錯了什麼或誤解了嗎?

任何幫助將不勝感激,謝謝!

我這是怎麼生成的日誌:

HashMap<String, String> log = new HashMap<String, String>(); 
log.put("core_pool_size", Integer.toString(producerThreadPool.getCorePoolSize())); 
log.put("scheduled_tasks", Long.toString(producerThreadPool.getTaskCount())); 
log.put("pool_size", Integer.toString(producerThreadPool.getPoolSize())); 
log.put("active_count", Integer.toString(producerThreadPool.getActiveCount())); 
log.put("queued_count", Integer.toString(producerThreadPool.getQueue().size())); 
String gson_str = gson.toJson(log); 
+1

該日誌消息是如何生成的? – jtahlborn 2012-07-23 18:23:00

+1

你能給出一個代碼重現這個例子嗎? – 2012-07-23 19:10:49

+1

您能否提供一個SSCCE來重現這一點,因爲給定newFixedThreadPool和ThreadPoolExecutor的源代碼,我看不出這是如何實現的。 – 2012-07-23 21:00:20

回答

2

根據文檔ThreadPoolExecutor.getActiveCount()只給出一個大概數,這是非常公平的考慮獲取精確值所需的開銷。所以當你看到'28'時,它實際上可能並不是28個併發運行的線程,但是在函數調用期間,它計數了28個線程。