How do I make a delay in Java?

前端 未结 8 1391
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

提交回复
热议问题