我正在寻找Java计时器示例,并在下面找到了以下代码 http://www.javaprogrammingforums.com/java-se-api-tutorials/883-how-use-timer-java.html
但是如果你运行样本,虽然现在打印定时器停止...它不会返回到命令提示符。这至少是使用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();
}
}
}
答案 0 :(得分:6)
它不会返回到您的命令提示符,因为它不会这样做。
Timer创建单个非deamon线程来运行所有任务。除非你问它,它不会终止线程。当您使用task.cancel()
方法时,您只需取消当前任务,而不是整个计时器仍处于活动状态,并准备做其他事情。
要终止计时器,您应该调用其stop()
方法,即timer.stop();
答案 1 :(得分:4)
在实际程序中,你会保留一个计时器对象的副本,当关闭程序时,请执行timer.cancel()。
对于这个简单的例子,我在timer.schedule(t,0,2000)之后添加了下面的代码;
try {
Thread.sleep(20000);
} catch(InterruptedException ex) {
System.out.println("caught " + ex.getMessage());
}
timer.cancel();
}
答案 2 :(得分: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();
}
}
}