class BoundedCounter {
protected int count;
protected int min;
protected int max;
public BoundedCounter(int minimum, int maximum) {
min = minimum;
max = maximum;
count = min;
}
public BoundedCounter(int maximum) {
min = 0;
max = maximum;
count = min;
}
public BoundedCounter() {
min = 0;
max = 10;
count = min;
}
public synchronized int count() {
return count;
}
public synchronized void inc() throws InterruptedException {
awaitUnderMax();
setCount(count+1);
}
public synchronized void dec() throws InterruptedException {
awaitOverMin();
setCount(count-1);
}
protected void setCount(int newValue) {
count = newValue;
notifyAll();
}
protected void awaitUnderMax() throws InterruptedException {
while (count == max) wait();
}
protected void awaitOverMin() throws InterruptedException {
while (count == min) wait();
}
}