【问题标题】:Time interval in JavaJava中的时间间隔
【发布时间】:2023-04-07 15:46:01
【问题描述】:

如何在时间间隔后调用方法? 例如,如果想在 2 秒后在屏幕上打印一条语句,它的过程是什么?

System.out.println("Printing statement after every 2 seconds");

【问题讨论】:

标签: java time intervals


【解决方案1】:

答案是同时使用 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 秒的打印间隔,但如果您想在一次打印后停止它,那将是很困难的。

也不要在代码中混合线程,而无需线程即可!

希望这会有所帮助!

【讨论】:

  • 为什么要使用两个Timer?摇摆和实用?为什么不直接将来自swing.Timer 的所有actionPerformed() 来自util.Timerrun() 中?
  • 谢谢亲爱的!您给定的解决方案对我有用。
【解决方案2】:

创建一个类:

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

    }
}

【讨论】:

    【解决方案3】:

    可以使用Timer类来实现

    new Timer().scheduleAtFixedRate(new TimerTask(){
                @Override
                public void run(){
                   System.out.println("print after every 5 seconds");
                }
            },0,5000);
            
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 2019-03-23
      • 2017-01-27
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多