1

我正在寻找一个 Java 计时器示例,并在 http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-timer-java.html找到了以下代码

但是,如果您运行该示例,尽管它确实打印 Timer stop now... 它不会返回到命令提示符。这至少是我使用 cmd.exe 在我的 Windows XP 机器上发生的情况。

为什么在这种情况下它不将控制权返回到提示符?

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

它不会返回到您的命令提示符,因为它不应该这样做。Timer 创建单个非守护线程来运行所有任务。除非您提出要求,否则它不会终止线程。当您执行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

您需要使用计时器显式终止计时器。取消(),例如:

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 回答