This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread Questions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread Questions" Watch "Thread Questions" New topic
Author

Thread Questions

Abhay Agarwal
Ranch Hand

Joined: Feb 29, 2008
Posts: 1086
    
    1

Hi

I am not able to understand the behaviour of below mentioned codes
Pleasse explain

Code A -

public class Run {
public static void main(String[] args) {
System.out.print("A ");
final Object test = new Object();
synchronized (test) {
test.notifyAll();
}
System.out.println("B");
}
}
Output is - “A B”


========================

Code B -

public class Run {
public static void main(String[] args) {
System.out.print("A ");
synchronized (new Object()) {
new Object().notifyAll();
}
System.out.println("B");
}
}
Output - It prints “A ” and an exception is thrown






Oracle Java Web Service Developer (1z0-897), Oracle certified Java 7 Programmer, SCJA 1.0, SCJP 5.0, SCWCD 5.0, Oracle SQL Fundamentals I
Ryan Beckett
Ranch Hand

Joined: Feb 22, 2009
Posts: 192
There are no other threads waiting for the monitor on your synchronized object, so main() continues to execute. When notifyAll() is called there are no other threads in the waiting state. So, the scheduler runs a thread in the Runnable state. main() is in the Runnable state.

In B,



You must call notifyAll() on a synchronized object. An IllegalMonitorStateException should have been thrown.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread Questions