Write a Java program to implement Producer Consumer using wait/notify

The Producer Consumer problem is an example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer. Both shares a common fixed-sized buffer as a queue. The producer’s job is to produce data in the buffer and start again. At the same time, the consumer is consuming the data. The problem is to make sure that the producer won’t try to add data into the buffer if it’s full and the consumer won’t try to remove data from an empty buffer.

This problem can be solved using wait and notify. Below program illustrates how to solve this.

public class ProducerConsumerDemo {

	public static void main(String[] args) {
		final Queue<Integer> queue = new LinkedList<>();
		int maxsize = 10;
		Producer producer = new Producer(queue, maxsize, "Producer");
		Consumer consumer = new Consumer(queue, maxsize, "Consumer");
		Random random = new Random();
		int i = random.nextInt();
		System.out.println("produce same" + i);
		producer.start();
		consumer.start();
	}
}

class Producer extends Thread {
	private final Queue<Integer> queue;
	private final int maxSize;

	public Producer(Queue<Integer> queue, int maxSize, String name) {
		this.queue = queue;
		this.maxSize = maxSize;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (queue) {
				if (queue.size() == maxSize) {
					try {
						System.out.println("Queue is full");
						queue.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				Random random = new Random();
				int i = random.nextInt();
				System.out.println("Producing value : " + i);
				queue.add(i);
				queue.notifyAll();
			}
		}
	}
}

class Consumer extends Thread {
	private final Queue<Integer> queue;
	private final int maxSize;

	public Consumer(Queue<Integer> queue, int maxSize, String name) {
		super(name);
		this.queue = queue;
		this.maxSize = maxSize;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (queue) {
				while (queue.isEmpty()) {
					try {
						System.out.println("Queue is empty");
						queue.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				queue.remove();
				System.out.println("Consuming value");
				queue.notifyAll();
			}
		}
	}
}

Author: Mahesh

Technical Lead with 10 plus years of experience in developing web applications using Java/J2EE and web technologies. Strong in design and integration problem solving skills. Ability to learn, unlearn and relearn with strong written and verbal communications.