1

私はJavaタイマーのサンプルを探していて、以下のコードを http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-timer-java.htmlで見つけました。

ただし、サンプルを実行すると、印刷は実行されますが、タイマーは停止します...コマンドプロンプトに戻りません。これは、少なくともcmd.exeを使用しているWindowsXPマシンで起こっていることです。

この場合、なぜプロンプトに制御を戻さないのですか?

import java.util.Timer;
import java.util.TimerTask;

public class TimerSample {

    public static void main(String[] args) {
        //1- Taking an instance of Timer class.
        Timer timer = new Timer("Printer");

        //2- Taking an instance of class contains your repeated method.
        MyTask t = new MyTask();


        //TimerTask is a class implements Runnable interface so
        //You have to override run method with your certain code black

        //Second Parameter is the specified the Starting Time for your timer in
        //MilliSeconds or Date

        //Third Parameter is the specified the Period between consecutive
        //calling for the method.

    timer.schedule(t, 0, 2000);

    }
}

class MyTask extends TimerTask {
    //times member represent calling times.
    private int times = 0;


    public void run() {
        times++;
        if (times <= 5) {
            System.out.println("I'm alive...");
        } else {
            System.out.println("Timer stops now...");

            //Stop Timer.
            this.cancel();
        }
    }
}
4

3 に答える 3

6

予期されていないため、コマンドプロンプトに戻りません。タイマーは、すべてのタスクを実行するための単一の非デーモンスレッドを作成します。あなたがそれを求めない限り、それはスレッドを終了しません。メソッドを実行task.cancel()すると、現在のタスクをキャンセルするだけで、まだ生きていて他のことを実行する準備ができているタイマー全体ではありません。

タイマーを終了するには、そのstop()メソッドを呼び出す必要があります。timer.stop();

于 2012-10-08T20:49:59.930 に答える
4

実際のプログラムでは、タイマーオブジェクトのコピーを保持し、たとえばプログラムを閉じる場合は、timer.cancel()を実行します。

この簡単な例では、timer.schedule(t、0、2000);の後に以下のコードを追加しました。

try {
   Thread.sleep(20000);
    } catch(InterruptedException ex) {
    System.out.println("caught " + ex.getMessage());
    }

    timer.cancel();

    }
于 2012-10-09T11:50:03.723 に答える
1

タイマーを使用してタイマーを明示的に終了する必要があります。cancel()、例:

class MyTask extends TimerTask {
 private int times = 0;
 private Timer timer;


 public MyTask(Timer timer) {
    this.timer = timer;
 }

 public void run() {
    times++;
    if (times <= 5) {
        System.out.println("I'm alive...");
    } else {
        System.out.println("Timer stops now...");

        //Stop Timer.
        this.cancel();
        this.timer.cancel();
    }
  }
}
于 2012-10-08T21:01:46.413 に答える