具有有界队列的 Java 线程池
我正在使用 java.util.concurrent 的 Executors
类,用于创建固定线程池,用于为 Web 服务器运行请求处理程序:
static ExecutorService newFixedThreadPool(int nThreads)
描述如下:
创建一个线程池,该线程池重用一组在共享无界共享队列上运行的固定线程。
但是,我正在寻找线程池实现,它将执行完全相同的操作,除了有界队列之外。有这样的实现吗?或者我是否需要为固定线程池实现自己的包装器?
I'm using java.util.concurrent
's Executors
class to create a fixed thread pool for running request handlers for a web server:
static ExecutorService newFixedThreadPool(int nThreads)
and the description is:
Creates a thread pool that reuses a fixed set of threads operating off a shared unbounded queue.
However, I am looking for thread pool implementation which will do the exact same thing, except with a bounded queue. Is there such an implementation? Or do I need to implement my own wrapper for the fixed thread pool?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您想要做的是新建自己的 ExecutorService,可能使用 ThreadPoolExecutor。 ThreadPoolExecutor 有一个构造函数,它接受 BlockingQueue 并获取您使用的有界队列,例如 ArrayBlockingQueue 正确构建边界。您还可以包含 RejectedExecutionHandler 以确定队列已满时要做什么,或者保留对阻塞队列的引用并使用 Offer 方法。
这是一个小例子:
What you want to do is new your own ExecutorService, probably using ThreadPoolExecutor. ThreadPoolExecutor has a constructor which takes a BlockingQueue and to get a bounded queue you use for example ArrayBlockingQueue properly constructed for bounding. You can also include a RejectedExecutionHandler in order to determine what to do when your queue is full, or hang on to a reference to the blocking queue and use the offer methods.
Here's a mini example:
创建一个ThreadPoolexecutor 并在其中传递合适的 BlockingQueue 实现。例如,您可以传入 ArrayBlockingQueue 在ThreadPoolExecutor构造函数中得到想要的效果。
Create a ThreadPoolexecutor and pass suitable BlockingQueue implementation in it. for e.g. you can pass in a ArrayBlockingQueue in the ThreadPoolExecutor constructor to get the desired effect.
我已经用 Semaphore 我用它来限制提交给 ExecutorService 的任务。
例如:
I've solved this with a Semaphore which I use to throttle tasks being submitted to the
ExecutorService
.Eg:
当您创建 ThreadPoolExecutor 时,您可以给它一个有界的 BlockingQueue 和 RejectedExecutionHandler,以便您可以控制达到限制时发生的情况。默认行为是抛出 RejectedExecutionException。
您还可以定义自己的线程工厂来控制线程名称并使它们成为守护线程。
When you create a ThreadPoolExecutor you can give it a bounded BlockingQueue and a RejectedExecutionHandler so you can control what happens when the limit is reached. The default behaviour is to throw a RejectedExecutionException.
You can also define you own thread factory to control the thread names and make them daemon threads.