Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Thread.sleep(0) and Thread.yield() statements equivalent?

Are these two statement equivalent?

Thread.sleep(0); Thread.yield(); 
like image 272
Prady Avatar asked Oct 21 '09 12:10

Prady


People also ask

What is the difference between yield () and sleep ()?

Sleep() causes the currently executing thread to sleep (temporarily cease execution). Yield() causes the currently executing thread object to temporarily pause and allow other threads to execute.

Can sleep () method causes another thread to sleep?

Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t. sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

What is the yield () method used in threads?

A yield() method is a static method of Thread class and it can stop the currently executing thread and will give a chance to other waiting threads of the same priority. If in case there are no waiting threads or if all the waiting threads have low priority then the same thread will continue its execution.

Why thread sleep is not recommended?

If given a wait of 5000 Milliseconds(5 seconds) and an element just take just 1-2 seconds to load, script will still wait for another 3 seconds which is bad as it is unnecessarily increasing the execution time. So thread. sleep() increases the execution time in cases where elements are loaded in no due time.


1 Answers

No. The most obvious difference is that sleep() throws the (checked) InterruptedException. In practice, the effect may be almost the same, but it's entirely implementation-dependant.

I'd wager that doing each a million times in a row would take much longer for sleep(), since system timer granularity probably often causes it to actually sleep for a non-negligible amount of time.

like image 137
Michael Borgwardt Avatar answered Oct 01 '22 02:10

Michael Borgwardt