java Java中的时间间隔
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31268818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Time interval in Java
提问by Naveed Jamali
how to call a method after a time interval? e.g if want to print a statement on screen after 2 second, what is its procedure?
如何在时间间隔后调用方法?例如,如果想在 2 秒后在屏幕上打印一条语句,它的程序是什么?
System.out.println("Printing statement after every 2 seconds");
回答by
The answer is using the javax.swing.Timer and java.util.Timer together:
答案是将 javax.swing.Timer 和 java.util.Timer 一起使用:
private static javax.swing.Timer t;
public static void main(String[] args) {
t = null;
t = new Timer(2000,new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Printing statement after every 2 seconds");
//t.stop(); // if you want only one print uncomment this line
}
});
java.util.Timer tt = new java.util.Timer(false);
tt.schedule(new TimerTask() {
@Override
public void run() {
t.start();
}
}, 0);
}
Obviously you can achieve the printing intervals of 2 seconds with the use of java.util.Timer only, but if you want to stop it after one printing it would be difficult somehow.
显然,您可以仅使用 java.util.Timer 来实现 2 秒的打印间隔,但是如果您想在一次打印后停止它,那将很难。
Also do not mix threads in your code while you can do it without threads!
也不要在您的代码中混合线程,而您可以在没有线程的情况下进行!
Hope this would be helpful!
希望这会有所帮助!
回答by Vishnu
Create a Class:
创建一个类:
class SayHello extends TimerTask {
public void run() {
System.out.println("Printing statement after every 2 seconds");
}
}
Call the same from your main method:
从您的主要方法中调用相同的方法:
public class sample {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new SayHello(), 2000, 2000);
}
}