本文介绍了Java中的时间间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

how to call a method after a time interval?e.g if want to print a statement on screen after 2 second, what is its procedure?

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


推荐答案

答案是使用javax.swing.Timer和java.util.Timer在一起:

The answer is using the javax.swing.Timer and java.util.Timer together:

    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可以达到2秒的打印间隔。仅限util.Timer,但是如果你想在一次打印后停止它,那么就会很难。

Obviously you can achieve the printing intervals of 2 seconds with the use of java.util.Timer only, but if you want to stop it after one printing it would be difficult somehow.

同样不要在你的代码中混合使用线程而不用线程!

Also do not mix threads in your code while you can do it without threads!

希望这会有所帮助!

这篇关于Java中的时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 00:16
查看更多