我想创建一个 ThreadPoolExecutor
,当它达到最大大小并且队列已满时,submit()
方法 blocks 尝试添加新任务时。我是否需要为此实现自定义 RejectedExecutionHandler
或者是否有使用标准 Java 库来执行此操作的现有方法?
最佳答案
我刚刚找到的一种可能的解决方案:
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
的东西,因为它似乎是处理这种情况的标准方法。
关于java - ThreadPoolExecutor 的 submit() 方法饱和后如何阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2001086/