How do I make a delay in Java?

前端 未结 8 1393
Happy的楠姐
Happy的楠姐 2020-11-22 08:24

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

while (true) {
    if (i == 3) {
        i         


        
相关标签:
8条回答
  • 2020-11-22 09:11

    Using TimeUnit.SECONDS.sleep(1); or Thread.sleep(1000); Is acceptable way to do it. In both cases you have to catch InterruptedExceptionwhich makes your code Bulky.There is an Open Source java library called MgntUtils (written by me) that provides utility that already deals with InterruptedException inside. So your code would just include one line:

    TimeUtils.sleepFor(1, TimeUnit.SECONDS);
    

    See the javadoc here. You can access library from Maven Central or from Github. The article explaining about the library could be found here

    0 讨论(0)
  • 2020-11-22 09:12

    Use this:

    public static void wait(int ms)
    {
        try
        {
            Thread.sleep(ms);
        }
        catch(InterruptedException ex)
        {
            Thread.currentThread().interrupt();
        }
    }
    

    and, then you can call this method anywhere like:

    wait(1000);
    
    0 讨论(0)
提交回复
热议问题