你可以动态调整一个java.util.concurrent.ThreadPoolExecutor,同时它仍然有任务等待 [英] Can you dynamically resize a java.util.concurrent.ThreadPoolExecutor while it still has tasks waiting

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

问题描述

我使用java.util.concurrent.ThreadPoolExecutor来并行处理多个项目。虽然线程本身工作正常,有时我们遇到其他资源约束,由于在线程中发生的操作,这使我们想减少池中的线程数。我想知道是否有一个方法来减少线程的数量,而线程实际工作。我知道你可以调用setMaximumPoolSize()和/或setCorePoolSize(),但这些只是调整池一旦线程变为空闲,但它们不会变得空闲,直到没有任务在队列中等待。

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. 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 。这将有效地导致线程死亡,并且由于执行器将高于最大值,不会创建新的。

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天全站免登陆