在程序中添加延迟

yiw*_*wei 1 java

我想在程序中使用Thread.sleep(1000)命令添加一个延迟(所以在继续之前让它停止1秒),但这意味着我还需要添加throws InterruptedException.但是,我不知道该把它放在哪里.

我的代码现在基本上看起来像这样:

public static void main(String[] args) {
    Clock myClock = new Clock;   // new clock object.

    while (true) {
        myClock.tick();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的另一课:

public class Clock {
    // .. some constructors and stuff

    public void tick() {
        secondHand.draw();   // redraws the second hand to update every second
    }

    // .. some more methods and stuff
}
Run Code Online (Sandbox Code Playgroud)

我想tick()每1秒调用一次该方法,但我不知道在哪里可以放入Thread.sleepthrows InterruptedException语句.任何帮助,将不胜感激.此外,我可以通过其他方式输入我的时钟滴答和/或更新也会有所帮助!

Vik*_*dor 5

我想每1秒调用一次tick()方法

调用之后tick(),对当前线程进行如下调整:

public static void main(String[] args) {
    Clock myClock = new Clock;   // new clock object.

    while (true) {
        myClock.tick();
        // wait for a second.
        try {
            Thread.sleep(1000);
        }
        catch (InterruptedException ie) {
            // Handle the exception
        }
    }
}
Run Code Online (Sandbox Code Playgroud)