Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

java - Thread.sleep vs. TimeUnit.SECONDS.sleep

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...