This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronized" Watch "synchronized" New topic
Author

synchronized

wei liu
Ranch Hand

Joined: Dec 06, 2001
Posts: 56
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

Joined: Oct 25, 2000
Posts: 7292

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


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: synchronized
 
Similar Threads
monitor and object lock
A Thread question from JQuest
Threads: Doubt
Quiz #56
Urgent ..one more Thread ....