Looking for a Tutor Near You?

Post Learning Requirement »
x

Choose Country Code

x

Direction

x

Ask a Question

x

x
x
x
Hire a Tutor

Java Concurrency - Producer-Consumer Pattern Using Wait & Notify

Loading...

Published in: Computer Science
485 Views

This is an example solution of the Producer-Consumer pattern using wait & notify

Somenath M / Kolkata

6 years of teaching experience

Qualification: BE - Electronics & TeleCommunication from IIEST

Teaches: Computer Science, IT & Computer Subjects, Mathematics, Data Structures, Computer, IT, C / C++, Java And J2EE, Android Training

Contact this Tutor
  1. Class ProducerConsumerQueue (thread-safe class) package com.somitsoIutions.training.java.ProducerConsumerProbIem; import java. util.Vector; public class ProducerConsumerQueue { Vector sharedQueue = new Vector(); private final int SIZE public ProducerConsumerQueue public int getSlZE return SIZE public synchronized void produce(int i) throws InterruptedException while(sharedQueue.size() = SIZE System.out.println("Queue is full" + Thread.currentThread() + "is waiting, size = sharedQueue.size()); wait o; sharedQueue.add(i); notifyAll o; public synchronized int consume() throws InterruptedException while(sharedQueue.isEmpty()){ System.out.println("Queue is empty Il + Thread.currentThread().getName() + " is waiting , size: Il + sharedQueue.size()); wait o; int retVal = sharedQueue.remove(0); notifyAll o; return retVal
  2. Class Producer package com.somitsoIutions.training.java.ProducerConsumerProbIem; public class Producer implements Runnable private final ProducerConsumerQueue sharedQueue, private final int SIZE public Producer(ProducerConsumerQueue queue sharedQueue = queue this.SlZE = sharedQueue .getSlZE(); @Override public void run // TODO Auto-generated method stub for (int • = 0; i
  3. public Consumer(ProducerConsumerQueue queue sharedQueue = queue, this.SlZE = sharedQueue .getSlZE(); @Override public void run // TODO Auto-generated method stub while (true){ try{ int val — sharedQueue.consume(); a); Thread.sleep(50); catch (InterruptedException ex Class Main package com.somitsolutions.training.java.ProducerConsumerProbIem; public class Main { public static void main(String[] args ProducerConsumerQueue sharedQueue = new ProducerConsumerQueue o; Thread prodThread = new Thread(new Producer(sharedQueue " Producer"); Thread consThread = new Thread(new Consumer(sharedQueue "Consumer"); prodThread.start(); consThread.start();