Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Questions

 
Abhay Agarwal
Ranch Hand
Posts: 1376
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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





 
Ryan Beckett
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic