如果 ThreadPoolExecutor 的 submit() 方法被饱和,如何让它阻塞?

2022-08-31 09:38:19

我想创建一个这样的方法,当它达到其最大大小并且队列已满时,该方法在尝试添加新任务时会阻塞。我是否需要为此实现自定义,或者是否有一种现有的方法来使用标准Java库来执行此操作?ThreadPoolExecutorsubmit()RejectedExecutionHandler


答案 1

我刚刚找到的可能的解决方案之一:

public class BoundedExecutor {
    private final Executor exec;
    private final Semaphore semaphore;

    public BoundedExecutor(Executor exec, int bound) {
        this.exec = exec;
        this.semaphore = new Semaphore(bound);
    }

    public void submitTask(final Runnable command)
            throws InterruptedException, RejectedExecutionException {
        semaphore.acquire();
        try {
            exec.execute(new Runnable() {
                public void run() {
                    try {
                        command.run();
                    } finally {
                        semaphore.release();
                    }
                }
            });
        } catch (RejectedExecutionException e) {
            semaphore.release();
            throw e;
        }
    }
}

还有其他解决方案吗?我更喜欢基于此的东西,因为它似乎是处理这种情况的标准方法。RejectedExecutionHandler


答案 2

您可以使用 ThreadPoolExecutor 和阻塞队列:

public class ImageManager {
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(blockQueueSize);
    RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
    private ExecutorService executorService =  new ThreadPoolExecutor(numOfThread, numOfThread, 
        0L, TimeUnit.MILLISECONDS, blockingQueue, rejectedExecutionHandler);

    private int downloadThumbnail(String fileListPath){
        executorService.submit(new yourRunnable());
    }
}

推荐