具有有限队列的Java线程池 [英] Java Thread Pool with a Bounded Queue
问题描述
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)
,描述为:
创建一个线程池,该线程池将重用一组固定的线程,这些线程在共享的 unbounded 队列之外运行.
但是,我正在寻找实现与 bounded 队列相同的功能的线程池.有这样的实现吗?还是我需要为固定线程池实现自己的包装器?
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?
推荐答案
您想要做的是新建自己的ExecutorService,可能使用 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.
这是一个小例子:
BlockingQueue<Runnable> linkedBlockingDeque = new LinkedBlockingDeque<Runnable>(
100);
ExecutorService executorService = new ThreadPoolExecutor(1, 10, 30,
TimeUnit.SECONDS, linkedBlockingDeque,
new ThreadPoolExecutor.CallerRunsPolicy());
这篇关于具有有限队列的Java线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!