java.util.concurrent.ThreadPoolExecutor 在等待任务时动态调整大小 [英] Dynamic resizing of java.util.concurrent.ThreadPoolExecutor while it has waiting tasks

查看:16
本文介绍了java.util.concurrent.ThreadPoolExecutor 在等待任务时动态调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 java.util.concurrent.ThreadPoolExecutor 来并行处理多个项目.尽管线程本身运行良好,但有时我们会因线程中发生的操作而遇到其他资源限制,这使我们想要调低池中的线程数.

I'm working with a java.util.concurrent.ThreadPoolExecutor to process a number of items in parallel. Although the threading itself works fine, at times we've run into other resource constraints due to actions happening in the threads, which made us want to dial down the number of Threads in the pool.

我想知道是否有办法在线程实际工作时调低线程数.我知道您可以调用 setMaximumPoolSize() 和/或 setCorePoolSize(),但是这些只会在线程空闲时调整池的大小,但直到线程空闲时它们才会空闲队列中没有等待的任务.

I'd like to know if there's a way to dial down the number of the threads while the threads are actually working. I know that you can call setMaximumPoolSize() and/or setCorePoolSize(), but these only resize the pool once threads become idle, but they don't become idle until there are no tasks waiting in the queue.

推荐答案

据我所知,这是不可能的.

As far as I can tell, this is not possible in a nice clean way.

您可以实现 beforeExecute 方法来检查一些布尔值并强制线程暂时停止.请记住,它们将包含一个在重新启用之前不会执行的任务.

You can implement the beforeExecute method to check some boolean value and force threads to halt temporarily. Keep in mind, they will contain a task which will not be executed until they are re-enabled.

或者,您可以实现 afterExecute 在饱和时抛出 RuntimeException.这将有效地导致线程死亡,并且由于 Executor 将高于最大值,因此不会创建新的.

Alternatively, you can implement afterExecute to throw a RuntimeException when you are saturated. This will effectively cause the Thread to die and since the Executor will be above the max, no new one would be created.

我也不建议你这样做.相反,尝试找到一些其他方法来控制导致您出现问题的任务的并发执行.可能是在一个单独的线程池中执行它们,并且工作线程数量更有限.

I don't recommend you do either. Instead, try to find some other way of controlling concurrent execution of the tasks which are causing you a problem. Possibly by executing them in a separate thread pool with a more limited number of workers.

这篇关于java.util.concurrent.ThreadPoolExecutor 在等待任务时动态调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆