• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

I'm not 'getting' sleep()

 
Mike Cunningham
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In one book, it says the sleep method will allow time for other threads to run. In another book, it says that any thread that goes to sleep does not give up ownership of any monitors (a.k.a. locks).
How can another thread run on the object if the sleep method does not give up ownership.
First book was Exam Cram.
Second book was Java 2 Passport.
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It just means that if a thread is holding a lock on an object and it sleeps, it will continue to hold the lock while it sleeps.
Contrast this with wait(), where the thread will give up it's lock while it is waiting.
public synchronized void methodA(){

Thread.sleep(10000); //while this thread sleeps, no other threads can run this method!
}
public synchronized void methodB(){
wait(); //thread gives up lock on this object; other threads can call this method while the first thread waits.
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic