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 Vs. Thread 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 "Thread Vs. Thread" Watch "Thread Vs. Thread" New topic

Thread Vs. Thread

Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
Can some one explain why the first thread runs printing A and B , where as the second thread throws an exception.
The source is

Is it because in the second program the object doesnot have a refernce name?

[ September 10, 2008: Message edited by: Nabila Mohammad ]

The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Ankit Garg

Joined: Aug 03, 2008
Posts: 9453

The second one throws MonitorStateException. This is because when you do this

synchronized(new Object())//separate object
new Object.notifyAll();//separate object

as you may know that you must hold the lock of the object that you call wait, notify and notifyAll on. But in this case, the synchronized block uses a different object and the notifyAll call uses a separate object of the Object class..

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
ankit kumar
Ranch Hand

Joined: Apr 28, 2008
Posts: 108
ya in the second progrmme you are creating again the new Object . you are not using the previous object.

Cleared SCJP 1.5 | Cleared SCWCD 5.0
SCDJWS 6 in progress.....
Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
Why didn't i think of that....
I agree. Here's the link:
subject: Thread Vs. Thread
It's not a secret anymore!