• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread

 
sweety sinha
Ranch Hand
Posts: 76
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this code is from: SCJP 6 Mock exam for Threads � Niko�s java blog.mht



it print A and gives runtime exception

but if modified like this it compiles and run fine


so why first code is getting exception and second code runs fine?
 
Rekha Srinath
Ranch Hand
Posts: 178
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In Line 1, you are synchronizing on a newly created object but on Line 2, you are calling notifyall () on an entirely-different object that is newly created again.
 
M Srilatha
Ranch Hand
Posts: 137
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
wait(), notify(), and notifyAll() must be called from within a synchronized
context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock.


In the first code sample, main thread has acquired lock on the object which is created in 2 line and its invoking the notifyAll() method on a new objet which is created inside the synchorized block. As the main thread doesnt own the lock on the object on which notifyAll() is invoked, it will throw runtime exception "IllegalMonitorStateException".

In the second example, the thread is trying to invoke the notifyAll() method on object r and it owns the lock on r. Thats the reason code compiles and runs properly!
 
sweety sinha
Ranch Hand
Posts: 76
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks Rekha Srinath & M SRILATHA for your response
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic