Java 是否有可索引的多队列线程池?

Does Java have an indexable multi-queue thread pool?(Java 是否有可索引的多队列线程池?)

本文介绍了Java 是否有可索引的多队列线程池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有这样的 Java 类:

Is there a Java class such that:

  1. 可以通过 id 添加可执行任务,保证所有具有相同 id 的任务不会同时运行
  2. 线程数可以限制为固定数量

一个朴素的地图解决方案很容易解决(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 是否有可索引的多队列线程池?

基础教程推荐