Java provides a very efficient way through which multiple threads can communicate with each other. This way reduces the CPU’s idle time, that means a process where a thread is paused running in its critical section(region) and another thread is allowed to enter(lock) in the same critical section to be executed. This technique is called as inter-threaded communication. It is also called as co-operation. It is implemented by some methods, such as :
these methods are defined in java.lang package and can only be called within synchronized code.
It causes current thread to release the lock and wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed. The current thread must own this object's monitor, so it must be called from the synchronized method only otherwise it will throw exception. The general form of wait() method is:
public final void wait()throws InterruptedException : waits until object is notified.
public final void wait(long timeout)throws InterruptedException : waits for the specified amount of time.
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation. Syntax: public final void notify().
Wakes up all threads that are waiting on this object's monitor. The general form is :
public final void notifyAll()
Note:The wait(), notify(), and notifyAll() methods are defined in Object class not Thread class.
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. A thread sends an interrupt by invoking interrupt() on the Thread object for the thread to be interrupted. If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException. There are some methods provided by the Thread class for thread interruption.
let's see an example of interrupting a thread that stops working. If we don't want to stop the thread, we can handle it where sleep() or wait() method is invoked.