繁体   English   中英

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

[英]I Need To Shutdown A ScheduledExecutorService, But Need To Start It Up When Needed

我为这个游戏做了一个不错的系统更新功能,我在这里编写代码:

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();
    ...

关闭时,您将获得提交到调度程序的任务列表,并且可以使用此列表创建新任务。 调度程序一旦停止就无法启动-因为线程池已死并且所有工作线程也都已死。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM