java 在程序中添加延迟

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13132207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:36:48  来源:igfitidea点击:

Adding a delay in programs

java

提问by yiwei

I want to add a delay in my program using the Thread.sleep(1000)command (so making it stop for 1 second before continuing) but this means I also need to add the throws InterruptedException. However, I'm not sure where to put it.

我想使用Thread.sleep(1000)命令在我的程序中添加延迟(因此在继续之前让它停止 1 秒)但这意味着我还需要添加throws InterruptedException. 但是,我不确定把它放在哪里。

My code basically looks like this right now:

我的代码现在基本上是这样的:

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

    while (true) {
        myClock.tick();
    }
}

My other class:

我的另一堂课:

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
}

I want to only call the tick()method every 1 second, but I don't know where I can put the Thread.sleepand throws InterruptedExceptionstatements. Any help would be appreciated. Also any input on other ways I can make my clock tick and/or update would be helpful too!

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

回答by Vikdor

I want to only call the tick() method every 1 second

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

After the call to tick(), put a sleep on the current thread as follows:

调用 后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
        }
    }
}

回答by travega

Depending on the flow of your program you will want to put the Thread.sleep(1000);statement into your controlling logic. By this I mean that whatever logic calls your tick()method would by convention be the best place to introduce your logic control - in this case your Thread.sleep(1000);statement.

根据您的程序流程,您可能希望将Thread.sleep(1000);语句放入您的控制逻辑中。我的意思是,tick()按照惯例,任何调用您的方法的逻辑都是引入逻辑控制的最佳位置 - 在这种情况下是您的Thread.sleep(1000);语句。

Alas your calling logic should look something like this:

唉,你的调用逻辑应该是这样的:

try {
    while (true) {
        Thread.sleep(1000);
        myClock.tick();
    }
} catch(InterruptedException e) {
    System.err.println("Something went wrong");
}

This approach ensures that if you have other controlling logic accessing your tick()method then it won't be tied into the 1 second delay. Different clients usually have different needs...

这种方法确保如果您有其他控制逻辑访问您的tick()方法,那么它不会与 1 秒延迟相关联。不同的客户通常有不同的需求...

I prefer to wrap the entire while loop in the try catch block for scalability safe readability... By this I mean the if the logic in you tick()method gets more complex and you end up throwing more exceptions then you can simply add the catch clause to the one try catch block like so:

我更喜欢将整个 while 循环包装在 try catch 块中以获得可伸缩性安全可读性......我的意思是如果你tick()方法中的逻辑变得更复杂并且你最终抛出更多异常,那么你可以简单地将 catch 子句添加到一个 try catch 块像这样:

try {
    while (true) {
        Thread.sleep(1000);
        myClock.tick();
    }
} catch(InterruptedException e) {
    System.err.println("Something went wrong");
} catch(SomeNewExcetion e) {
    System.err.println("Something went wrong");
} catch(SomeOtherNewExceptoion e) {
    System.err.println("Something went wrong");
} catch(SomeFinalException e) {
    System.err.println("Something went wrong");
}

回答by MadProgrammer

You could use either javax.swing.Timeror java.util.Timerto achieve the same results.

您可以使用javax.swing.Timerjava.util.Timer来获得相同的结果。

The javax.swing.Timerhas the advantage of when it's triggered, the ActionPerformedmethod is executed within the Event Dispatching Thread, making updates to the UI easier.

javax.swing.Timer优点是在触发时,该ActionPerformed方法在事件调度线程中执行,从而更容易更新 UI。

java.util.Timer

java.util.定时器

timer = new Timer();
timer.schedule(new TickTock (), 1000);

public class TickTock extends TimerTask {
    public void run() {
        System.out.println("Tick tock!");
    }
}

javax.swing.Timer

javax.swing.Timer

Timer timer = new Timer(1000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Tick tock!");
        repaint();
    }
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();

You can have read through How to Use Swing Timersfor more info on javax.swing.Timer

您可以阅读如何使用摇摆计时器了解更多信息javax.swing.Timer

回答by Tinman

Although I would not normally suggest it.

虽然我通常不会建议它。

In this case you do not really need to code for this being interrupted. Hide it by wrapping with a runtime exception.

在这种情况下,您实际上不需要为此被中断编码。通过用运行时异常包装来隐藏它。

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

    public void tick() {
       secondHand.draw();   // redraws the second hand to update every second
    }
    public void wait() {
       try {
           Thread.sleep(1000)
       } catch(InterruptedException e) {
           throw new RuntimeException("Don't know how to handle this", e);
       }
    }
   // .. some more methods and stuff
}

回答by HASNEN LAXMIDHAR

its Very Simple in java

它在java中非常简单

TimeUnit.SECONDS.sleep(2);