睡眠和时间单元

如果我要调用 Java 线程进入睡眠状态,有没有理由选择其中一种形式?

Thread.sleep(x)

或者

TimeUnit.SECONDS.sleep(y)
99847 次浏览

TimeUnit.SECONDS.sleep(x) will call Thread.sleep after validating that the timeout is positive. This means that as opposed to Thread.sleep, an IllegalArgumentException will not be thrown when the timeout is negative.

Other than that, 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);
}
}

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.