Java中的时间间隔
如何在一个时间间隔后调用方法? e、 g如果想在2秒钟后在屏幕上打印一条语句,其步骤是什么Java中的时间间隔,java,time,intervals,Java,Time,Intervals,如何在一个时间间隔后调用方法? e、 g如果想在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 =
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秒的打印间隔,但如果要在一次打印后停止打印,可能会有些困难
也不要在代码中混用线程,因为你可以不用线程
希望这会有帮助 答案是同时使用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秒的打印间隔,但如果要在一次打印后停止打印,可能会有些困难
也不要在代码中混用线程,因为你可以不用线程
希望这会有帮助 创建一个类:
class SayHello extends TimerTask {
public void run() {
System.out.println("Printing statement after every 2 seconds");
}
}
从主方法调用相同的函数:
public class sample {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new SayHello(), 2000, 2000);
}
}
创建一个类:
class SayHello extends TimerTask {
public void run() {
System.out.println("Printing statement after every 2 seconds");
}
}
从主方法调用相同的函数:
public class sample {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new SayHello(), 2000, 2000);
}
}
为什么要使用两个计时器?swing和util?为什么不直接从
util.Timer
运行run()
中执行actionPerformed()
中的swing.Timer
中的所有actionPerformed()!你给出的解决方案对我有效。为什么要使用两个计时器?swing和util?为什么不直接从util.Timer
运行run()
中执行actionPerformed()
中的swing.Timer
中的所有actionPerformed()!你给出的解决方案对我有效。