线程池有多个限制 [英] Thread-Pool with multiple limits
问题描述
我想要一个线程池,该线程池最多提供X个线程来处理任务,到目前为止没有问题.但是,每个提交的任务都可以指定一个特定的IO目标(例如Y).
I want a Thread-Pool that provides a maximum of X Threads to process tasks, so far no problem. However each submitted Task can specify an IO-Target which is specifically limited (say Y).
因此,提交的IOTask返回目标"google.com",其限制为4(Y),而该池的全局限制为16(X).我想提交10个google.com-tasks,其中只有4个并行处理,并且池中有12个线程可用于其他任务.
So a submitted IOTask returns the target "google.com" with limit 4 (Y) and the pool has a global limit 16 (X). I want to submit 10 google.com-tasks where only 4 are processed in parallel and the pool has 12 threads free for other tasks.
我该如何实现?
推荐答案
您可以将两个ExecutorService实例包装在自定义类中,并按如下所示手动管理任务的提交:
You can wrap two ExecutorService instances in a custom class and manually manage the submission of tasks as follows:
class ExecutorWrapper {
private ExecutorService ioExec = Executors.newFixedThreadPool(4);
private ExecutorService genExec = Executors.newFixedThreadPool(12);
public Future<?> submit(final IOTask task) {
return ioExec.submit(task);
}
public Future<?> submit(final Runnable task) {
return genExec.submit(task);
}
}
interface IOTask extends Runnable {}
这使您可以使用4个线程来执行IO操作,而让其他12个线程来处理其他任务.
This allows you to use 4 threads to do the IO operations and leaves the other 12 threads to service the other tasks.
这篇关于线程池有多个限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!