我正在做一个应用程序java和场景构建器,我会创建一个newScheduledThreadPool(1)
。当我单击按钮时,接下来当我再次单击按钮时,执行器必须暂停,当我再次单击按钮时,执行器将恢复其工作。
这是我的代码:
public class ExecutorThreadReadDatabase {
static Logger logger = MyLog4J.getInstance();
private static boolean stopThread ;
private static ExecutorThreadReadDatabase executorThreadReadDatabase;
private ScheduledExecutorService executor;
public ExecutorThreadReadDatabase() {
executor = Executors.newScheduledThreadPool(1);
}
public static ExecutorThreadReadDatabase getInstance() {
if (executorThreadReadDatabase == null) {
logger.info("null");
return new ExecutorThreadReadDatabase();
} else {
logger.info("not nullo");
return executorThreadReadDatabase;
}
}
public void readToDatabaseFromNetworkServer() {
logger.info("lo stop è : "+stopThread);
executor.scheduleAtFixedRate(RunnableThread.getInstance(), 0, 5,
TimeUnit.SECONDS);
}
public void stopT() {
logger.info("stoppo l' executor");
executor.shutdown();
executor.wait()
}
抱歉我的英语不好
最佳答案
我认为最简单的方法是在 ExecutorThreadReadDatabase
中维护一个“暂停”标志。 ,并包裹 Runnable
您在另一个 Runnable
中提交给执行人,在运行之前检查暂停标志的值:
public class ExecutorThreadReadDatabase {
private volatile boolean paused = false;
// ...
public void readToDatabaseFromNetworkServer() {
logger.info("lo stop è : "+stopThread);
RunnableThread rt = RunnableThread.getInstance();
Runnable r = new Runnable() {
@Override public void run() {
if (paused) return;
rt.run();
}
};
executor.scheduleAtFixedRate(r, 0, 5, TimeUnit.SECONDS);
}
关于java - 如何暂停newScheduledThreadPool?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47749274/