import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class PCQueueUsingLock<T> {
private final int MAX_CAPACITY = 5;
private final Object[] items = new Object[MAX_CAPACITY];
private final Lock lock = new ReentrantLock();
private final Condition notFull = lock.newCondition();
private final Condition notEmpty = lock.newCondition();
private int putptr, takeptr;
private int count;
public void put(T x) throws InterruptedException {
lock.lock();
try {
while (count == items.length) {
System.out.println("queue full, wait for consumer");
notFull.await();
}
items[putptr] = x;
if (++putptr == items.length) {
putptr = 0;
}
++count;
notEmpty.signal();
System.out.print("after put: ");
for(Object obj : items) {
System.out.print(obj + " ");
}
System.out.println();
} finally {
lock.unlock();
}
}
@SuppressWarnings("unchecked")
public T take() throws InterruptedException {
lock.lock();
try {
while (count == 0) {
System.out.println("queue empty, wait for producer");
notEmpty.await();
}
Object x = items[takeptr];
items[takeptr] = null;
if (++takeptr == items.length) {
takeptr = 0;
}
--count;
notFull.signal();
System.out.print("after take: ");
for(Object obj : items) {
System.out.print(obj + " ");
}
System.out.println();
return (T)x;
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Random rand = new Random(System.currentTimeMillis());
final int round = 10;
PCQueueUsingLock<Integer> pcQueue = new PCQueueUsingLock<>();
final CountDownLatch startGate = new CountDownLatch(1);
Thread p = new Thread(){
public void run() {
try {
startGate.await();
for(int i=0; i<round; i++) {
pcQueue.put(rand.nextInt(10));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
};
Thread c = new Thread(){
public void run() {
try {
startGate.await();
for(int i=0; i<round; i++) {
pcQueue.take();
Thread.sleep((long) (3000*Math.random()));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
};
p.start();
c.start();
startGate.countDown();
}
}