I have read that Thread.sleep()
will pause the currently running thread for the time specified after which it goes back to runnable state waiting for it's turn to run.
Also, if called from synchronized
context, sleep()
doesn't release the lock it holds. So I was wondering when it will release the lock. If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block.
I am not sure if I am asking valid question. But please help me out.
If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block. Quite simply, other threads will not be able to enter code that's synchronized on the same object that the sleeping thread.
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.
Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.
Wait() method releases lock during Synchronization. Sleep() method does not release the lock on object during Synchronization. Wait() should be called only from Synchronized context.
So I was wondering when it will release the lock.
It will release the lock upon exit from the synchronized
block, and not earlier.
If the thread, put on sleep, never gets the chance to run so it will always keep the lock with itself and then how other threads get to enter synchronized methods/block.
Quite simply, other threads will not be able to enter code that's synchronized on the same object that the sleeping thread.
To summarize, calling Thread.sleep()
from a synchronized
block is likely not a good idea.
If you use Object.wait
instead of Thread.sleep
, the lock from the synchronized block will be released.
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