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

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 "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: 9280

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: 106
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
(SCEA/OCMJEA) 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
Similar Threads
Thread Question from Sun's Free Mock Test
synch in threads
Thread Questions
synchronized block