File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 EJB 3 in Action this week in the EJB and other Java EE Technologies 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
 
jQuery in Action, 2nd edition
 
subject: synchronized
 
Similar Threads
Quiz #56
monitor and object lock
A Thread question from JQuest
Threads: Doubt
Urgent ..one more Thread ....