As currently executing thread while it encounters the call sleep()
then thread moves immediately into sleeping stat. Whereas for yield()
thread moves into runnable state / ready state.
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 sleep() method is a static method of Thread class and it makes the thread sleep/stop working for a specific amount of time. The sleep() method throws an InterruptedException if a thread is interrupted by other threads, that means Thread.
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.
The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution. This was just a clear and basic explanation, if you want more than that then continue reading.
We can prevent a thread from execution by using any of the 3 methods of Thread class:
yield()
method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority or higher priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent.
join()
If any executing thread t1 calls join()
on t2 (i.e. t2.join()
) immediately t1 will enter into waiting state until t2 completes its execution.
sleep()
Based on our requirement we can make a thread to be in sleeping state for a specified period of time (hope not much explanation required for our favorite method).
sleep()
causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield()
basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
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