0

私はこのゲーム用に素晴らしいシステム アップデート機能を作成しました。コードは次のとおりです。

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 を入力するとスケジューラーの実行を停止する方法はありますが、数字 > を入力すると (数回) スケジューラーを再開できます。

4

2 に答える 2

2

一度シャットダウンすると、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();
    ...
于 2012-05-24T19:54:50.260 に答える
1

シャットダウンすると、スケジューラに送信されたタスクのリストが表示され、このリストを使用して新しいタスクを作成できます。スレッド プールが停止し、すべてのワーカー スレッドも停止しているため、一度停止するとスケジューラを開始できません。

于 2012-05-24T19:46:39.493 に答える