【发布时间】:2023-04-07 15:46:01
【问题描述】:
如何在时间间隔后调用方法? 例如,如果想在 2 秒后在屏幕上打印一条语句,它的过程是什么?
System.out.println("Printing statement after every 2 seconds");
【问题讨论】:
如何在时间间隔后调用方法? 例如,如果想在 2 秒后在屏幕上打印一条语句,它的过程是什么?
System.out.println("Printing statement after every 2 seconds");
【问题讨论】:
答案是同时使用 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);
}
显然,您可以仅使用 java.util.Timer 来实现 2 秒的打印间隔,但如果您想在一次打印后停止它,那将是很困难的。
也不要在代码中混合线程,而无需线程即可!
希望这会有所帮助!
【讨论】:
swing.Timer 的所有actionPerformed() 来自util.Timer 的run() 中?
创建一个类:
class SayHello extends TimerTask {
public void run() {
System.out.println("Printing statement after every 2 seconds");
}
}
在你的 main 方法中调用同样的方法:
public class sample {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new SayHello(), 2000, 2000);
}
}
【讨论】:
可以使用Timer类来实现
new Timer().scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
System.out.println("print after every 5 seconds");
}
},0,5000);
【讨论】: