这种疑难杂症是覆盖在this blog post:如预期
线程池的这种结构根本不起作用。这是由于ThreadPoolExecutor中的逻辑,如果未能向队列提供任务,则会添加新线程。在我们的例子中,我们使用一个无界的LinkedBlockingQueue,我们可以随时提供一个任务给队列。这实际上意味着我们永远不会超过核心池大小并达到最大池大小。
如果您还需要将最小值与最大池大小分离,则必须进行一些扩展编码。我不知道Java库或Apache Commons中存在的解决方案。解决方案是创建一个知道TPE的耦合的BlockingQueue
,并且如果它知道TPE没有可用的线程,然后手动重新请求,它将会拒绝任务。它在链接的文章中有更详细的介绍。最终,你的建设将是这样的:
public static ExecutorService newScalingThreadPool(int min, int max, long keepAliveTime) {
ScalingQueue queue = new ScalingQueue();
ThreadPoolExecutor executor =
new ScalingThreadPoolExecutor(min, max, keepAliveTime, TimeUnit.MILLISECONDS, queue);
executor.setRejectedExecutionHandler(new ForceQueuePolicy());
queue.setThreadPoolExecutor(executor);
return executor;
}
然而,更简单的设置corePoolSize
到maxPoolSize
,不要担心这个无稽之谈。
相关问题http://stackoverflow.com/questions/19528304/how-to-get-the-threadpoolexecutor-to-increase-threads-to-max-before-queueing/19528305#19528305 – Gray 2013-10-22 21:38:47