Does Java have an indexable multi-queue thread pool?(Java 是否有可索引的多队列线程池?)
问题描述
是否有这样的 Java 类:
Is there a Java class such that:
- 可以通过 id 添加可执行任务,保证所有具有相同 id 的任务不会同时运行
- 线程数可以限制为固定数量
一个朴素的地图解决方案很容易解决(1),但很难管理(2).同样,我所知道的所有线程池类都将从单个队列中提取,这意味着 (1) 无法保证.
A naive solution of a Map would easily solve (1), but it would be difficult to manage (2). Similarly, all thread pooling classes that I know of will pull from a single queue, meaning (1) is not guaranteed.
欢迎涉及外部库的解决方案.
Solutions involving external libraries are welcome.
推荐答案
如果你没有找到开箱即用的东西,那么推出你自己的应该不难.您可以做的一件事是将每个任务包装在一个简单的类中,该类读取每个 id 唯一的队列,例如:
If you don't find something that does this out of the box, it shouldn't be hard to roll your own. One thing you could do is to wrap each task in a simple class that reads on a queue unique per id, e.g.:
public static class SerialCaller<T> implements Callable<T> {
private final BlockingQueue<Caller<T>> delegates;
public SerialCaller(BLockingQueue<Caller<T>> delegates) {
this.delegates = delegates;
}
public T call() throws Exception {
return delegates.take().call();
}
}
维护 id 到队列的映射应该很容易,以便提交任务.即满足条件(1),然后可以寻找条件(2)的简单解法,如执行者.newFixedThreadPool
It should be easy to maintain a map of ids to queues for submitting tasks. That satisfies condition (1), and then you can look for simple solutions to condition (2), such as Executors. newFixedThreadPool
这篇关于Java 是否有可索引的多队列线程池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 是否有可索引的多队列线程池?


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- 大摇大摆的枚举 2022-01-01