/** * Lock-based FIFO Queue * This example was borrowed from Marieke Huisman lecture notes. * It does not contain annotations yet because STaVe must first be * extended to support java.util.concurrent * Author: Pedro de Carvalho Gomes * Date: 2016-01-19 */ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; class Producer extends Thread { LockBasedFifo myfifo; Producer(LockBasedFifo pfifo) { myfifo = pfifo; } public void run() { // Enqueue itself //System.out.println("Producer: " + Thread.currentThread().getId()); myfifo.enq(this); } } class Consumer extends Thread { LockBasedFifo myfifo; Consumer(LockBasedFifo pfifo) { myfifo = pfifo; } public void run() { // Dequeue something //System.out.println("Consumer: " + Thread.currentThread().getId()); myfifo.deq(); } } public class LockBasedFifo { private int tail=0; private int head=0; private Object[] items; private final ReentrantLock lock; private final Condition notFull; private final Condition notEmpty; LockBasedFifo(int pnumels) { if (pnumels > 1) items = new Object[pnumels]; else items = new Object[1]; lock = new ReentrantLock(); notFull = lock.newCondition(); notEmpty = lock.newCondition(); } public void enq(Object pitem) { lock.lock(); try { while (tail-head == items.length) notFull.await(); items[tail % items.length] = pitem; tail++; notEmpty.signal(); } catch (InterruptedException e) { // Ignoring exceptional flow } finally { lock.unlock(); } } public Object deq() { Object litem = null; lock.lock(); try { while (tail == head) notEmpty.await(); litem = items[head % items.length]; head++; notFull.signal(); } catch (InterruptedException e) { // Ignoring exceptional flow } finally { lock.unlock(); } return litem; } public static void main( String[] argv) { LockBasedFifo myshared = new LockBasedFifo(1); Consumer[] mycons = new Consumer[1]; for( int i = 0; i < mycons.length; i++) { mycons[i] = new Consumer(myshared); } Producer[] myprod = new Producer[2]; for( int i = 0; i < myprod.length; i++) { myprod[i] = new Producer(myshared); } for( int i = 0; i < mycons.length; i++) { mycons[i].start(); } for( int i = 0; i < myprod.length; i++) { myprod[i].start(); } //System.out.println("Exiting..."); } }