// This example is from the book _Java Threads_ by Scott Oaks and Henry Wong.
// Written by Scott Oaks and Henry Wong.
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.
// Sample ResourceThrottle -- Chapter 4, p. 79.
public class ResourceThrottle {
private int resourcecount = 0;
private int resourcemax = 1;
public ResourceThrottle (int max) {
resourcecount = 0;
resourcemax = max;
}
public synchronized void getResource (int numberof) {
while (true) {
if ((resourcecount + numberof) <= resourcemax) {
resourcecount += numberof;
break;
}
try {
wait();
} catch (Exception e) {}
}
}
public synchronized void freeResource (int numberof) {
resourcecount -= numberof;
notifyAll();
}
}
|