Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.sleep vs. TimeUnit.SECONDS.sleep

Tags:

java

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) 
like image 305
Rachel Avatar asked Mar 06 '12 16:03

Rachel


People also ask

How long is thread sleep 1000?

For example, with thread. sleep(1000), you intended 1,000 milliseconds, but it could potentially sleep for more than 1,000 milliseconds too as it waits for its turn in the scheduler. Each thread has its own use of CPU and virtual memory.

Why thread sleep is not recommended Java?

Thread. sleep is bad! It blocks the current thread and renders it unusable for further work.

What are the two time units which sleep method supports?

sleep using the specified time unit. It has 7 constants – DAYS , HOURS , MICROSECONDS , MILLISECONDS , MINUTES , NANOSECONDS , SECONDS for convenience. To sleep in seconds, use TimeUnit. SECONDS .


1 Answers

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);     } } 
like image 184
assylias Avatar answered Oct 12 '22 06:10

assylias