Thread.sleep vs. TimeUnit.SECONDS.sleep

前端 未结 2 1917
忘了有多久
忘了有多久 2020-12-12 15:51

If I\'m going to have a call to have a Java Thread go to sleep, is there a reason to prefer one of these forms over the other?

Thread.sleep(x)
2条回答
  •  佛祖请我去吃肉
    2020-12-12 16:20

    TimeUnit.SECONDS.sleep(x) will call Thread.sleep. The only difference is readability and using TimeUnit is probably easier to understand for non obvious durations (for example: Thread.sleep(180000) vs. TimeUnit.MINUTES.sleep(3)).

    For reference, see below the code of sleep() in TimeUnit:

    public void sleep(long timeout) throws InterruptedException {
        if (timeout > 0) {
            long ms = toMillis(timeout);
            int ns = excessNanos(timeout, ms);
            Thread.sleep(ms, ns);
        }
    }
    

提交回复
热议问题