Why sleep()
and yield()
methods are defined as static
methods in java.lang.Thread
class
?
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.
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.
On the other hand, Thread. sleep() is a static method that can be called from any context. Thread. sleep() pauses the current thread and does not release any locks.
The main difference between wait and sleep is that wait() method releases the acquired monitor when the thread is waiting while Thread. sleep() method keeps the lock or monitor even if the thread is waiting.
The code would only execute when someXThread
was executing, in which case telling someYThread
to yield would be pointless. So since the only thread worth calling yield
on is the current thread, they make the method static
so you won't waste time trying to call yield
on some other thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With