File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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 Spring in Action this week in the Spring 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: 1158
    
    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