Forums Register Login

sleep() method concept

+Pie Number of slices to send: Send
Hi Guys,
Here is the piece of code

synchronized(LOCK) {
Thread.sleep(1000); // LOCK is held
}

.

We know that the sleep method() does not release the lock. Hence, no other object can access the above piece of code even
if this thread is asleep. So, I am confused why is sleep used in this context! sleep() is used to give other threads a chance to get back into
runnable( or may be running). Aint't it?
Please help.

Thanks
Faisal
+Pie Number of slices to send: Send
No, the sleep() method does not release the lock or give chance to other threads, just sleeping. You may be confused with Object.wait(). Use wait() if you want to do something like sleep() but does release the lock.
+Pie Number of slices to send: Send
 

So, I am confused why is sleep used in this context! sleep() is used to give other threads a chance to get back into
runnable( or may be running). Aint't it?



First, there really is no context provided in your code snipped, so it is impossible to say why it was used where you question it.

But sleep() is used to stop this thread from using CPU cycles. This might be used to let other threads a chance to do work and advance in their own sequences, or it might be used simply because this thread has nothing to do for a little while. Why would you specifically put a sleep inside a synchronized block without anything else? I think I need more context to see why - I could imagine there might be a reason to do it for testing an proof-of-concept purposes (create a situation where a thread holds on to a lock for a period of time and simulate doing work). Or if there is a reason to prevent the lock from being taken by another thread for a fixed period of time for some reason. Or maybe there are multiple threads that could reach this code and you want to make sure that they sleep() in sequence rather than in parallel.
What do you have to say for yourself? Hmmm? Anything? And you call yourself a tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 821 times.
Similar Threads
Is my Understanding Correct ?
waiting to sleep
Yeild method
Threads and Synchronization
Is Thread.sleep() synchronised method ?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 00:42:56.