import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; public class MonitorLocks { private final Lock _lock = new ReentrantLock(); private final Condition _notFull = _lock.newCondition(); private final Condition _notEmpty = _lock.newCondition(); private int[] _data; private int _index; public MonitorLocks(int capacity) { _data = new int[capacity]; _index = 0; } public void add(int number) { // aquire the lock _lock.lock(); try { // room for more data? while ( _index >= _data.length ) { try { _notFull.await(); // wait for room } catch (InterruptedException ignored) { } } // add number and notify waiting threads _data[_index++] = number; _notEmpty.signal(); // signal that the buffer isn't empty } finally { _lock.unlock(); // in case something goes wrong } } public int get() { // aquire the lock _lock.lock(); try { // is data to retreive? while ( _index <= 0 ) { try { _notEmpty.await(); // wait for data } catch (InterruptedException ignored) { } } // get number and notify waiting threads int out = _data[--_index]; _notFull.signal(); // signal that the buffer isn't full return out; } finally { _lock.unlock(); // in case something goes wrong } } }