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!