gpt4 book ai didi

java - 如何暂停newScheduledThreadPool?

转载 作者:行者123 更新时间:2023-12-02 11:53:15 27 4
gpt4 key购买 nike

我正在做一个应用程序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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com