具有有界队列的 Java 线程池

2022-09-01 07:30:56

我正在使用 的 Executors 类来创建一个固定的线程池,用于运行 Web 服务器的请求处理程序:java.util.concurrent

static ExecutorService  newFixedThreadPool(int nThreads) 

描述是:

创建一个线程池,该线程池重用一组对共享的无界队列运行的固定线程。

但是,我正在寻找线程池实现,它将执行完全相同的事情,除了有队列。有这样的实现吗?还是我需要为固定线程池实现自己的包装器?


答案 1

你想做的是更新你自己的ExperatorService,可能使用ThreadPoolExecutor。ThreadPoolExecutor有一个构造函数,它接受一个BlockningQueue,并获取一个有界队列,例如数组阻塞队列,正确构造用于边界。还可以包含 RejectedExecutionHandler,以确定在队列已满时要执行的操作,或者挂起对阻塞队列的引用并使用聘约方法。

下面是一个小示例:

BlockingQueue<Runnable> linkedBlockingDeque = new LinkedBlockingDeque<Runnable>(
    100);
ExecutorService executorService = new ThreadPoolExecutor(1, 10, 30,
    TimeUnit.SECONDS, linkedBlockingDeque,
    new ThreadPoolExecutor.CallerRunsPolicy());

答案 2

我已经用一个信号量解决了这个问题,我用它来限制提交到.ExecutorService

例如:

int threadCount = 10;
ExecutorService consumerPool = Executors.newFixedThreadPool(threadCount);

// set the permit count greater than thread count so that we 
// build up a limited buffer of waiting consumers
Semaphore semaphore = new Semaphore(threadCount * 100); 

for (int i = 0; i < 1000000; ++i) {
    semaphore.acquire(); // this might block waiting for a permit 
    Runnable consumer = () -> {
       try {
          doSomeWork(i);
       } finally {
          semaphore.release(); // release a permit 
       }
    };
    consumerPool.submit(consumer);
}