1)The wait and notify should be on the same object. what happens when they are acting on different objects.
1) Wait method waits for the acquisition of the lock on that particular object until some other
thread notifies it.
So if wait is waiting on an object and notification is happening for a different object, the wait will go on indefinitely until it gets interrupted. Notify will notify to any thread waiting on that object. Since no threads are waiting on the particular object, nothing takes place.
2)when the wait method is interrupted, if not, then whats the purpose of giving the InterruptedException in catch block.
When wait method is invoked, the thread goes on to wait state until some other thread notifies it. If some thread interrupts it, the thread comes back to normal thereby throwing an interrupted exception.
Look at the code below
:
In the above code u can see that there are two threads running.
1) Main thread
2) Thread object t1.
Now when t1 is run, it invokes wait method on the StringBuffer object. The main thread is also running side by side.
Main thread calls interrupt on thread t1. And so the thread t1 is interrupted.
what happens when the notify method is not given.
If the thread is waiting on that object and if it finds no notify method, it goes on indefinitely until the thread is interrupted. Look at my previous code. Just remove the interrupt statement and check the output.