mdelatorre

Producer / Consumer example in Java

Sep 5th, 2020
292
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.javatechie.multithreading;
  2.  
  3. import java.util.LinkedList;
  4. import java.util.Queue;
  5. import java.util.concurrent.locks.Condition;
  6. import java.util.concurrent.locks.ReentrantLock;
  7.  
  8. /**
  9.  * Consumer & Producer Example using lock and conditions
  10.  **/
  11. public class MyQueue<E> {
  12.  
  13.     Queue<E> myQueue = null;
  14.     int max;
  15.     ReentrantLock lock = new ReentrantLock();
  16.     Condition notEmpty = lock.newCondition();
  17.     Condition notFull = lock.newCondition();
  18.  
  19.     public MyQueue(int max) {
  20.         this.myQueue = new LinkedList<>();
  21.         this.max = max;
  22.     }
  23.  
  24.     /**
  25.      * Add element to queue
  26.      **/
  27.     public void addElement(E e) throws InterruptedException {
  28.         lock.lock();
  29.         try {
  30.             //check if queue size is full then wait
  31.             while (myQueue.size() == max) {
  32.                 notFull.await();
  33.             }
  34.             myQueue.add(e);
  35.             //notify to other thread (consumer thread)
  36.             notEmpty.signalAll();
  37.         } finally {
  38.             lock.unlock();
  39.         }
  40.     }
  41.  
  42.     /**
  43.      * Get element from queue
  44.      **/
  45.     public E get() throws InterruptedException {
  46.         lock.lock();
  47.         try {
  48.             //check if queue size is empty then wait
  49.             while (myQueue.isEmpty()) {
  50.                 notEmpty.await();
  51.             }
  52.             E object = myQueue.remove();
  53.             //notify to other thread (producer thread)
  54.             notFull.signalAll();
  55.             return object;
  56.         } finally {
  57.             lock.unlock();
  58.         }
  59.     }
  60. }
  61.  
Add Comment
Please, Sign In to add comment