Thread.sleep vs. TimeUnit.SECONDS.sleep

JavaSleep

Java Problem Overview


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)

or

TimeUnit.SECONDS.sleep(y)

Java Solutions


Solution 1 - Java

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);
    }
}

Solution 2 - Java

They are the same. I prefer the latter because it is more descriptive and allows to choose time unit (see TimeUnit): DAYS , HOURS , MICROSECONDS , MILLISECONDS , MINUTES , NANOSECONDS , SECONDS .

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRachelView Question on Stackoverflow
Solution 1 - JavaassyliasView Answer on Stackoverflow
Solution 2 - JavaTomasz NurkiewiczView Answer on Stackoverflow