Skip to main content

Posts

Showing posts with the label Producer consumer problem

Implementing the Producer Consumer Pattern Using Wait and Notify in Java

Below are the conditions for producer consumer pattern. We need to ensure that the thread should not be blocked either if the buffer is empty or full. This is achieved by calling wait() and notify() method on the lock object which is used to synchronized the block of code. Please note that it is important for both threads to synchronize on the same monitor / lock object. A producer produces values inside a buffer. A consumer consumes the values from this buffer. The buffer can be empty or full. Producer and consumer runs in their own thread. Note: wait() and notify() should not be called outside the synchronized code block Below is the example code : package com.refermynotes; public class ProducerConsumerExample { public static int[] buffer; public static Object lock = new Object(); public static int count; static class Producer{ public void produce(){ synchronized (lock) { if(isFull(buffer)){ try { lock.wait(); } catch...