0

Why is the second answer correct? What exception was thrown and why?

 wait*emphasized text*

P.S. Thanks for the answer!

Now I see that t1.wait() shall be inside synchronized(t1) - on t1, the same instance used to call wait(). Also this answer was helpful.

enter image description here

This is a free test taken from here

Code Complete
  • 3,146
  • 1
  • 15
  • 38

1 Answers1

4

Since this code calls t1.wait without holding the lock on t1 object - the IllegalMonitorStateException will be thrown - as is documented in Object::wait(time) method. This is a RuntimeException so it does not have to be specified in method signature. synchronized on Bees::go method will make sure that thread invoking this method will hold lock on Bees object - not t1 object.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63