为什么这个java计时器示例永远不会结束
我正在寻找一个Java计时器示例,并在 但是如果你运行这个示例,虽然它现在打印计时器停止了。。。它不会返回到命令提示符。这至少是使用cmd.exe在我的Windows XP计算机上发生的情况 在这种情况下,为什么不将控件返回到提示符为什么这个java计时器示例永远不会结束,java,timertask,Java,Timertask,我正在寻找一个Java计时器示例,并在 但是如果你运行这个示例,虽然它现在打印计时器停止了。。。它不会返回到命令提示符。这至少是使用cmd.exe在我的Windows XP计算机上发生的情况 在这种情况下,为什么不将控件返回到提示符 import java.util.Timer; import java.util.TimerTask; public class TimerSample { public static void main(String[] args) {
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();
}
}
}
它不会返回到命令提示符,因为不希望它返回到命令提示符。 计时器创建一个非deamon线程来运行所有任务。除非您要求,否则它不会终止线程。当您执行task.cancel方法时,您只需取消当前任务,而不是整个计时器,该计时器仍处于活动状态,准备执行其他操作
要终止计时器,应调用其停止方法,即timer.stop 它不会返回到命令提示符,因为不希望它返回到命令提示符。 计时器创建一个非deamon线程来运行所有任务。除非您要求,否则它不会终止线程。当您执行task.cancel方法时,您只需取消当前任务,而不是整个计时器,该计时器仍处于活动状态,准备执行其他操作
要终止计时器,应调用其停止方法,即timer.stop 您需要使用计时器显式终止计时器,例如:
您需要使用计时器显式终止计时器,例如:
在一个真实的程序中,你会保留一个timer对象的副本,当eg程序关闭时,做一个timer.cancel 对于这个简单的示例,我在timer.schedulet,0,2000之后添加了下面的代码
try {
Thread.sleep(20000);
} catch(InterruptedException ex) {
System.out.println("caught " + ex.getMessage());
}
timer.cancel();
}
在一个真实的程序中,你会保留一个timer对象的副本,当eg程序关闭时,做一个timer.cancel 对于这个简单的示例,我在timer.schedulet,0,2000之后添加了下面的代码
try {
Thread.sleep(20000);
} catch(InterruptedException ex) {
System.out.println("caught " + ex.getMessage());
}
timer.cancel();
}
计时器,停下?TimerTask或Timer有这样的功能吗?你的意思是停止线程?但是我该怎么做呢?API中有一条注释说线程停止是不安全的。它是Timer.cancel,而不是Timer.stop。表单是javax.swing.Timer,而不是java.util.Timertimer.stop?TimerTask或Timer有这样的功能吗?你的意思是停止线程?但是我该怎么做呢?API中有一条注释说线程停止是不安全的。它是Timer.cancel,而不是Timer.stop。您尝试编译的表单是javax.swing.Timer,而不是java.util.TimerId?没有。你试过编译吗?没有。