mjain

Producer Consumer Problem

Jun 19th, 2019
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. import java.util.LinkedList;
  2. import java.util.Queue;
  3.  
  4. public class ProCons {
  5.  
  6.     Queue<Integer> queue        = new LinkedList<Integer>();
  7.     int            max_capacity = 5;
  8.  
  9.     public void produce(int i) throws InterruptedException {
  10.         while (true) {
  11.             synchronized (this) {
  12.                 if (queue.size() == max_capacity) {
  13.                     wait();
  14.                 }
  15.                 System.out.println("Produced: " + i);
  16.                 queue.add(i);
  17.                 notify();
  18.                 Thread.sleep(1000);
  19.             }
  20.         }
  21.     }
  22.  
  23.     public void consume() throws InterruptedException {
  24.         while (true) {
  25.             synchronized (this) {
  26.                 if (queue.size() == 0) {
  27.                     wait();
  28.                 }
  29.                 int i = queue.poll();
  30.                 System.out.println("consumed: " + i);
  31.                 notify();
  32.                 Thread.sleep(1000);
  33.             }
  34.         }
  35.     }
  36.  
  37.     public static void main(String[] args) {
  38.         ProCons pc = new ProCons();
  39.  
  40.         Thread producerThread = new Thread(new Runnable() {
  41.             @Override
  42.             public void run() {
  43.                 try {
  44.                     pc.produce(100);
  45.                 } catch (InterruptedException e) {
  46.                     System.out.println("Exception in producer" + e.getMessage());
  47.                 }
  48.  
  49.             }
  50.         });
  51.  
  52.         Thread consumerThread = new Thread(new Runnable() {
  53.             @Override
  54.             public void run() {
  55.                 try {
  56.                     pc.consume();
  57.                 } catch (InterruptedException e) {
  58.                     System.out.println("Exception in consumer" + e.getMessage());
  59.                 }
  60.             }
  61.         });
  62.         try {
  63.             producerThread.start();
  64.             consumerThread.start();
  65.             producerThread.join();
  66.             consumerThread.join();
  67.         } catch (InterruptedException e) {
  68.             System.out.println("Exception " + e.getMessage());
  69.         }
  70.  
  71.     }
  72. }
Add Comment
Please, Sign In to add comment