如何在Java中的ExecutorService中暂停/恢复所有线程?
我向Java的executorservice提交了一堆作业,但我想以某种方式暂时暂停所有这些作业。最好的方法是什么?我该如何恢复?还是我这样做完全错误?我是否应该遵循其他想要实现的模式(即暂停/恢复执行服务的能力)?
回答:
为了回答我自己的问题,我PausableThreadPoolExecutor
在ThreadPoolExecutor
本身的javadocs中找到了一个示例。这是我使用番石榴显示器的版本:
import com.google.common.util.concurrent.Monitor;import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
public class PausableExecutor extends ScheduledThreadPoolExecutor {
private boolean isPaused;
private final Monitor monitor = new Monitor();
private final Monitor.Guard paused = new Monitor.Guard(monitor) {
@Override
public boolean isSatisfied() {
return isPaused;
}
};
private final Monitor.Guard notPaused = new Monitor.Guard(monitor) {
@Override
public boolean isSatisfied() {
return !isPaused;
}
};
public PausableExecutor(int corePoolSize, ThreadFactory threadFactory) {
super(corePoolSize, threadFactory);
}
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
monitor.enterWhenUninterruptibly(notPaused);
try {
monitor.waitForUninterruptibly(notPaused);
} finally {
monitor.leave();
}
}
public void pause() {
monitor.enterIf(notPaused);
try {
isPaused = true;
} finally {
monitor.leave();
}
}
public void resume() {
monitor.enterIf(paused);
try {
isPaused = false;
} finally {
monitor.leave();
}
}
}
以上是 如何在Java中的ExecutorService中暂停/恢复所有线程? 的全部内容, 来源链接: utcz.com/qa/398421.html