簡體   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