[英]How to limit a task from using all threads in a thread pool?
I'm using a thread pool to execute tasks in the background of my application. 我正在使用线程池在应用程序后台执行任务。 However, some of my tasks are heavier than others.
但是,我的某些任务比其他任务重。 So I'd like to limit the heavy tasks to a certain subset of the thread pool, thereby leaving at least a few threads open for any lightweight tasks to execute.
因此,我想将繁重的任务限制为线程池的某个子集,从而为任何轻量级任务留出至少几个线程。
Is there a simple way to do this? 有没有简单的方法可以做到这一点?
The most simple way is to use separate thread pools for different "tasks weight". 最简单的方法是对不同的“任务权重”使用单独的线程池。
Even you can create separate class which exposes separate methods for differents tasks. 甚至您可以创建单独的类,为不同的任务提供单独的方法。
As it was said, the cleanest way is to use a separate thread pool for heavy threads. 如前所述,最干净的方法是对重线程使用单独的线程池。
Another way is to use a Semaphore. 另一种方法是使用信号量。 Create a semaphore with a count of, for example, three.
创建一个数量为例如三个的信号量。 Heavy threads have to acquire() it first.
重线程必须首先获取()它。 Only three heavy ones would be able to do so.
只有三个笨重的人能够做到。 The rest will wait (or fail, if you use tryAcquire()).
其余的将等待(或失败,如果您使用tryAcquire())。
Of course, the thread needs to "know" it is a "heavy" one. 当然,线程需要“知道”它是一个“繁重的”线程。 For third-party threads it doesn't work, so see "two pools" approach again.
对于第三方线程,它不起作用,因此请再次参见“两个池”方法。 :-)
:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.