Thread Communication Using Wait and Notify in Java

By Arvind Rai, March 23, 2014
In java, threads can communicate to each other in many ways. One of the way is using wait and notify. wait() and notify() belongs to Object class in java. In our example we have a producer thread and second is consumer thread. Producer is adding element in a list and this value is being fetched by consumer. Here communication means producer will not add next element until consumer will fetch that. To achieve it producer will add the element in the list and will call wait() method. It stops executing and releases the lock on calling object. Now consumer starts executing and removes the value from the list. It notifies the producer and then goes into waiting state releasing the lock on calling object. Find the example.
WaitNotifyTest.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
public class WaitNotifyTest {
    private static Object lock = new Object();
    private static List<String> list = new ArrayList<String>();
    public static void main(String[] args) {
        new Producer().start();
        new Consumer().start();
    }
    static class Producer extends Thread {
        @Override
        public void run() {
            while (true){
            	synchronized (lock) {
            		if(list.size()==0){
            			System.out.println("Producer added A");
            			list.add("A");
            			try {
				    lock.wait();
				} catch (InterruptedException e) {
							e.printStackTrace();
				}
            		}
            		lock.notify();
            	}	
            }
        }
    }
    static class Consumer extends Thread{
        @Override
        public void run() {
           while (true){
        	   synchronized (lock) {
        		   if(list.size()==1){
        			   System.out.println("Consumer consumes A");
        			   list.remove(0);
        			   lock.notify();
        			   try {
					 lock.wait();
				   } catch (InterruptedException e) {
						e.printStackTrace();
				   }
        		   }
	                   try {
	                     Thread.sleep(1000);
	                   } catch (InterruptedException e) { e.printStackTrace(); }
	               
        	   }
           }   
        }
   }
} 
Find the output.
Producer added A
Consumer consumes A
Producer added A
Consumer consumes A
Producer added A
Consumer consumes A
Producer added A
Consumer consumes A
Producer added A
----------------
----------------
 
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us