Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronized

 
wei liu
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Read the following code, which is a part of a synchronized method of a monitor.

public synchronized void someMethod()
{
//lots of code
try
{
Thread.sleep(500);
}
catch(InterruptedException e)
{
//do some crap here.
}
//more and more code here
}
When the thread "goes to sleep" it releases the lock on the object.
The "sleeping" Threads always have the lock on the Object.
the ans is 2nd. why not the first? but if call Thread.wait();should the ans be the first one?
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once a thread enters a synchronized method, it has acquired the lock for that object instance. sleep() has no impact on locking whatsoever; which is why it's not a good idea to sleep with a lock in the first place.
wait() is not a Thread method -- a frequent misconception among beginners -- it's an Object method. This will make more and more sense with practice; threads call wait() on objects, not themselves.
In this code snippet, the lock is only released by exiting the method.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic