aspose file tools*
The moose likes Threads and Synchronization and the fly likes sleep() method concept Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "sleep() method concept" Watch "sleep() method concept" New topic
Author

sleep() method concept

Faisal syed
Ranch Hand

Joined: Mar 25, 2011
Posts: 35
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
Nam Ha Minh
Ranch Hand

Joined: Oct 31, 2011
Posts: 498

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.


PM Me If You Want to get Urgent Help on Java Programming
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

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.


Steve
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: sleep() method concept