package com.javatechie.multithreading;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* Consumer & Producer Example using lock and conditions
**/
public class MyQueue<E> {
Queue<E> myQueue = null;
int max;
ReentrantLock lock = new ReentrantLock();
Condition notEmpty = lock.newCondition();
Condition notFull = lock.newCondition();
public MyQueue(int max) {
this.myQueue = new LinkedList<>();
this.max = max;
}
/**
* Add element to queue
**/
public void addElement(E e) throws InterruptedException {
lock.lock();
try {
//check if queue size is full then wait
while (myQueue.size() == max) {
notFull.await();
}
myQueue.add(e);
//notify to other thread (consumer thread)
notEmpty.signalAll();
} finally {
lock.unlock();
}
}
/**
* Get element from queue
**/
public E get() throws InterruptedException {
lock.lock();
try {
//check if queue size is empty then wait
while (myQueue.isEmpty()) {
notEmpty.await();
}
E object = myQueue.remove();
//notify to other thread (producer thread)
notFull.signalAll();
return object;
} finally {
lock.unlock();
}
}
}
Comments