/* Code of Figure 14.8, pages 645-646 from Kenneth C. Louden, Programming Languages Principles and Practice 2nd Edition Copyright (C) Brooks-Cole/ITP, 2003 */ class Buffer { private final char[] buf; private int start = -1; private int end = -1; private int size = 0; private Semaphore nonFull, nonEmpty, mutEx; public Buffer(int length) { buf = new char[length]; nonFull = new Semaphore(length); nonEmpty = new Semaphore(0); mutEx = new Semaphore(1); } public boolean more() { return size > 0; } public void put(char ch) { try { nonFull.delay(); mutEx.delay(); end = (end+1) % buf.length; buf[end] = ch; size++; mutEx.signal(); nonEmpty.signal(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } public char get() { try { nonEmpty.delay(); mutEx.delay(); start = (start+1) % buf.length; char ch = buf[start]; size--; mutEx.signal(); nonFull.signal(); return ch; } catch (InterruptedException e) { Thread.currentThread().interrupt(); } return 0; } }