gpt4 book ai didi

java - 我需要关闭 ScheduledExecutorService,但需要在需要时启动它

转载 作者:行者123 更新时间:2023-12-02 00:22:09 25 4
gpt4 key购买 nike

我为这个游戏制作了一个甜蜜的系统更新功能,代码如下:

public static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private static CountDownThread countDownThread;
public static boolean running = false;

private static short updateSeconds;


public static void start() {
System.out.println("starting");
running = true;
countDownThread = new CountDownThread();
scheduler.scheduleWithFixedDelay(countDownThread, 0, 1000, TimeUnit.MILLISECONDS);
}

public static void stop() {
System.out.println("Stoping");
scheduler.shutdown();
running = false;
updateSeconds = 0;
System.out.println("Stopped");
}

public static void refresh() {
for (Player p : Static.world.players){
if (p.ready()) {
if (updateSeconds > 0) {
ActionSender.sendSystemUpdate(p, updateSeconds+1);
} else {
ActionSender.sendSystemUpdate(p, updateSeconds);
}
}
}
}

public static short getUpdateSeconds() {
return updateSeconds;
}

public static void setUpdateSeconds(short updateSeconds) {
SystemUpdateHandler.updateSeconds = (short) (updateSeconds);
}

public static class CountDownThread implements Runnable {

@Override
public void run() {
System.out.println(updateSeconds);
updateSeconds--;
if (updateSeconds <= 0) {
Static.server.restart();
scheduler.shutdown();
running = false;
}
}

}

}

也就是说,当系统更新计数器达到0时,服务器将自行重新启动。它工作正常,但问题就从这里开始

    case "update":
if (Short.parseShort(txtSystemUpdate.getText()) != 0) {
SystemUpdateHandler.setUpdateSeconds(Short.parseShort(txtSystemUpdate.getText()));
SystemUpdateHandler.refresh();
if (!SystemUpdateHandler.running) {
SystemUpdateHandler.start();
}
} else {
SystemUpdateHandler.stop();
for (Player p : Static.world.players){
if (p.ready()) {
ActionSender.sendSystemUpdate(p, 0);
}
}
}
break;

这就是我所说的,基本上如果我输入一个大于 0 的数字,程序就可以正常工作。但我想要它,所以如果我输入数字 0,调度程序将停止运行(以节省内存),因为除非我发送系统更新,否则不需要它。基本上,当我输入 0 时,如何停止调度程序运行,但当我输入数字 > 然后 0(多次)时,如何启动它呢?

最佳答案

一旦关闭,ExecutorService 就无法再次启动,因此请将其创建从变量声明中移出(并删除 Final),并在 start 方法中执行此操作:

//not static and not final, normal instance variable instead:
public ScheduledExecutorService scheduler;
...

//and create it in the start method isntead:
public static void start() {
System.out.println("starting");
scheduler = Executors.newSingleThreadScheduledExecutor();
...

关于java - 我需要关闭 ScheduledExecutorService,但需要在需要时启动它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10744208/

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