wait, notify and notifyAll

java

The 3 methods are all Object’s member not Thread’s. So you can call them at every class instance. It’s used when we want the thread to wait for some condition.

The methods can be called only when holding current object’s lock otherwise IllegalMonitorException will be thrown. When wait method is called, the hold lock will be released. And current thread will stay in the object’s “wait queue” until object’s notify or notifyAll method is called.

Notify and notifyAll are called to notify the waiting thread that the condition is met. Difference is that notify is to wake up one random thread but notifyAll is to wake up all threads. NotifyAll is preferred than the notify method for the system’s liveness consideration.

//Thread1
synchronized void run() {
	while(!condition){
		wait();
	}
	doSomething();
}

//Thread2
synchronized void run() {
    doSomething(); 
    notifyAll();
}