简体   繁体   English

如何限制任务使用线程池中的所有线程?

[英]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.

相关问题 Tomcat maxThreads立即达到:正在使用线程池中的这些线程是什么 - Tomcat maxThreads instantly reached: what is using these threads from the thread pool Fork-Join线程池中的长时间运行任务是否可以阻止所有线程? - Can a long running task in a Fork-Join thread pool block all threads? 如何使用java8 Labmdas和线程池实例化Object或调用setter来传递来自不同线程的值? - How to instantiate Object or call setter to pass values from different Threads using java8 Labmdas and thread pool? 如何使用invokeAll()让所有线程池完成他们的任务? - How to use invokeAll() to let all thread pool do their task? 如何确保线程被完全执行? (使用线程池) - How to make sure threads are being fully executed? (using thread pool) ExecutorService休眠线程池中的所有线程 - ExecutorService sleep all threads in thread pool 当任务通过执行器服务提交给线程池中的线程时,如何保证一次只能有1个线程占用一个同步任务? - When task is submitted to threads in a thread pool via executor service how to ensure that only 1 thread can occupy a synchronized task at a time? 如何为需要由多个线程处理的单个任务实现线程池? - How do I implement thread pool for the single task need to be handled by multiple threads? Java 执行器框架中线程池中的线程数限制? - Limit on number of threads in Thread pool in Java executors framework? 从Java中的线程池中删除空闲线程? - Removing idle threads from thread pool in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM