Thread.sleep vs TimeUnit.SECONDS.sleep

If I have a call for Java Thread to sleep, is there any reason to prefer one of these forms over another?

Thread.sleep(x) 

or

 TimeUnit.SECONDS.sleep(y) 
+47
java sleep
Mar 06 2018-12-12T00:
source share
2 answers

TimeUnit.SECONDS.sleep(x) will call Thread.sleep . The only difference is the readability and use of TimeUnit is probably easier to understand for non-obvious durations (e.g. Thread.sleep(180000) vs. TimeUnit.MINUTES.sleep(3) ).

For reference, see the sleep() code 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); } } 
+72
Mar 06 2018-12-12T00:
source share
— -

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

+6
Mar 06 2018-12-12T00:
source share



All Articles