Java中的时间间隔

如何在一段时间间隔后调用一个方法? 例如,如果想在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秒的打印间隔,但是如果你想在一次打印后停止它,那么某种程度上会很困难。

也可以在没有线程的情况下在代码中混合使用线程!

希望这会有所帮助!

创建一个类:

 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); } }