Java中的时间间隔

时间:2015-07-07 12:41:30

标签: java time intervals

如何在一段时间后调用一个方法? 例如,如果想在2秒后在屏幕上打印一个声明,它的程序是什么?

const

2 个答案:

答案 0 :(得分: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秒的打印间隔,但是如果你想在一次打印后停止它,那么某种程度上会很难。

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

希望这会有所帮助!

答案 1 :(得分:0)

创建一个类:

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

    }
}