my dog learned polymorphism
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronized" Watch "synchronized" New topic


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
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

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:
subject: synchronized
It's not a secret anymore!