Why is the second answer correct? What exception was thrown and why?
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.
This is a free test taken from here
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.