Yes. wait(), notify() and notifyAll() methods must be called withing synchronized context( synchronized block, synchronized method)..These methods are not in SCJP exam as per other ranchers comments. Serialization is also not in the exam it seems.
Rohit Ramachandran wrote:wait is thrown and caught
Actually, wait() is not an exception which can be thrown.
IllegalMonitorStateException is (also) thrown when wait() is called, as method is not synchronized.
But in that case, Ex-B is printed.
Joined: Sep 26, 2010
mohitkumar gupta wrote:
is it necessary to have wait,notify in synchronized block or method
Yes, it's necessary.
Wait and Notify provides a means of communication between threads which are synchronized on the same object.
When a Thread calls wait() method in synchronized context, it releases the object lock and waits.
Invoking notify() method from other thread occupying that object lock wakes up the waiting thread.