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

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

问题描述

是否存在这样的Java类:

Is there a Java class such that:

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

Map的幼稚解决方案很容易解决(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)的简单解决方案,例如

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是否有可索引的多队列线程池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆