Calling
notify() will wake up one thread that has called
wait() on the same object you called
notify() on.
Sadly, you didn't call
wait() and
notify() on the same object. Hint: in this case the type of your lock object is
Runnable, not
NotifyAndWaitExample2.
A few other remarks:
You should always call
wait() inside a loop that checks a condition.
wait() is allowed to return without any thread having called
notify() or
notifyAll(), so you need to communicate between the threads using a condition.
Don't use
synchronized in the method declaration, and don't synchronize on
this. 9 out of 10 times, your lock should be owned by the object you want to synchronize, and it shouldn't be available to the outside world. That means you should do something like this:
However, since
Java released the concurrency framework, you wouldn't use synchronized blocks anymore, and prefer Lock instead: