File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Synchronization Doubt? 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 "Thread Synchronization Doubt?" Watch "Thread Synchronization Doubt?" New topic

Thread Synchronization Doubt?

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9344

Hi Guys,

The following is from the K&B book. Page 720.

The explanation given as, "Notice in line 6 the code synchronizes itself with the object b- this is because in order to call wait() on the object. ThreadA must own a lock on b. For a thread to call wait() or notify(), the thread has to be the owner of the lock for that object.

So from my understanding, at line 6 which is in ThreadA, when we say synchronized(b), it means that ThreadA has locked ThreadB. Is that what I can infer?? This may sound dumb and stupid, but ranchers, please help me understand this.

Thanks in advance.

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9344


Anyone please help me with the above code please???
John Johnson
Ranch Hand

Joined: Nov 05, 2006
Posts: 39
Yes, you are correct. When you say synchronized(b) you are locking onto the instance of ThreadB (not the class itself). So while your thread is in that synchronized block, no other thread can access synchronized methods of that b instance, however, they still can run un-synhronized methods of that class.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Jothi, did you forget something in that ThreadB class? You can't just call notify like that. You are going to get an IllegalMonitorStateException in thread B.
[ December 16, 2006: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9344

Yes Barry,

I forgot the synchronized block.
I agree. Here's the link:
subject: Thread Synchronization Doubt?
Similar Threads
How wait() and notify() works?
Threads (wait method)
problem in understading wait(), notify() from kb6 book ?