Java FixedThreadPool不能使用set pool size?

时间:2012-07-23 18:18:45

标签: java threadpool threadpoolexecutor

我正在使用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 个答案:

答案 0 :(得分:2)

根据文档ThreadPoolExecutor.getActiveCount(),它只给出一个近似计数,考虑到获得准确值所需的开销,这是非常公平的。所以当你看到'28'时,它可能实际上并不是28个并发运行的线程,但是在函数调用期间,它计算了28个线程。