wait() and notify() in java

Previous
Next

wait, notify and notifyAll():

  • We can implement inter thread communication using these methods.
  • wait(), notify() and notifyAll() methods are belongs to Object class.
  • We must use these methods with synchronized context of java application.
  • wait() method causes the current thread to wait until another thread invokes the notify() or notifyAll() methods for that object.
  • The notify() method wakes up a single thread that is waiting on that object’s monitor.
  • The notifyAll() method wakes up all threads that are waiting on that object’s monitor.
  • A thread waits on an object’s monitor by calling one of the wait() method.
  • These methods can throw IllegalMonitorStateException if the current thread is not the owner of the object’s monitor.
public class Demo 
{
	static long secs = 3000;
	static boolean running = true;
	static Thread thread;
	public void start() 
	{
		System.out.println("Inside start() method");
		thread = new Thread(new Runnable() {
			public void run() 
			{
				print("Inside run() method");
				try 
				{
					Thread.sleep(secs);
				} 
				catch(InterruptedException e) 
				{
					Thread.currentThread().interrupt();
				}
				synchronized(Demo.this) 
				{
					running = false;
					Demo.this.notify();
				}
			}
		});
		thread.start();
	}
	public void join() throws InterruptedException 
	{
		print("Inside join() method");
		synchronized(this) 
		{
			while(running)
			{
				System.out.println("Waiting for the peer thread to finish.");
				wait(); //waiting, not running
			}
			System.out.println("Peer thread finished.");
		}
	}
	private void print(String s) 
	{
		System.out.println(s);
	}
	public static void main(String[] args) throws InterruptedException 
	{
		Demo d = new Demo();
		d.start();
		d.join();
   	}
}
Previous
Next

Add Comment

Courses Enquiry Form