1

私はJavaでソケットプログラミングに取り組んでいます。各接続でタイマーを使用する必要があり、次のコードのようにタイマーを使用しています:

this.timeoutTask = new TimeoutTask();
this.timeoutTimer = Executors.newSingleThreadScheduledExecutor();
private void startTimer(ConnectionState state) {
    int period;
    connectionState = state;
    period = connectionState.getTimeoutValue();
    future = timeoutTimer.scheduleAtFixedRate(timeoutTask, period, period, TimeUnit.MILLISECONDS);
}
 private void stopTimer() {

    if (timeoutTimer != null) {
        future.cancel(true);
    }

}

private void shutdownTimer() {

    timeoutTimer.shutdown();
    timeoutTask.cancel();
}

タイマーを一時停止するには「stopTimer」関数を使用し、タイマータスクを削除するには「shutdownTimer」関数を使用しています。しかし、このようにタイマーを使用すると、数千の時間が同時に生きているため、数千のタイマースレッドを実行することがあります。この問題を防ぐ最善の方法は何ですか?

4

1 に答える 1