purpose of wait() and notify() methods in Object class

As briefed in all methods of Object class these methods are final and defined in java.lang.Object class. Hence these methods are available in each and every class, because Object class is base class of all classes, in Java. These methods can be invoked only from synchronized block or synchronized method.
wait(); – It tells the calling thread to give up the lock and go to sleep until some other thread calls notify() method on same object.
notify(); -It wakes up one single thread that called wait() on the same object.
notifyAll(); – It wakes up all the threads that called wait() on the same object.
These methods can be used to solve producer consumer related problems.

Below is simple example in which Main thread invokes wait() on threadb, after threadb computes total sum, it invokes notify() method, so that Main thread gets the control, and prints total value.

public class NotifyWait {
	public static void main(String[] args) {
		NotifyWaitB b = new NotifyWaitB();
				System.out.println("A:waiting for b thread to complete...");
			}catch(Exception e) {
				System.out.println("Interrupted Exception:"+e.getMessage());
			System.out.println("Total is:"+b.total);

class NotifyWaitB extends Thread{
	int total;	
	public void run(){		
		System.out.println("in run() method of Child thread");
			for(int i=0;i<30;i++)
				total += i;				
			System.out.println("notify() invoked from Child thread");

Below is some real time example on using wait() and notify() methods.


Here Display Thread, need to continuously check(with a infinite loop or so) Packet Queue, to find if new Packets are available, which may not be a professional approach. As continuously checking Packet Queue, may waste CPU time, and may adversely affect performance of overall Application. This problem can be solved better, by using wait() and notify(). Below are the steps involved…

Downloader Thread downloads packets, adds to Queue.
Calls notify() method on Queue, which wakes up Display Thread.

Now display Thread reads packets from Queue, processes them.
Calls wait() method on Queue, which goes on sleep, until notify() is called by Downloader Thread.

You may also like to read:
how to use join() method between child threads?
how to avoid deadlock in threads
can a child thread start another child thread?