Java Reference
In-Depth Information
At the other extreme, the consumer must not be allowed to consume when there
is nothing to consume (i.e., when the resource level has reached zero). Thus, if the
resource level is at zero when method takeOne is executed, wait is called from
within a loop that continuously checks that the level is still at zero. The calling of
wait suspends the ConsumerClient thread and releases the lock on the shared
resource level variable, allowing any Producer to obtain it. When the resource level
is above zero, takeOne decrements the level and then calls method notifyAll to
'wake up' any waiting Producer thread.
The code for class Resource is shown below. Note that ResourceServer must
have access to the code for both Producer and Resource .
class Resource
{
private int numResources;
private fi nal int MAX = 5;
public Resource(int startLevel)
{
numResources = startLevel;
}
public int getLevel()
{
return numResources;
}
public synchronized int addOne()
{
try
{
while (numResources >= MAX)
wait();
numResources++;
//'Wake up' any waiting consumer…
notifyAll();
}
catch (InterruptedException interruptEx)
{
System.out.println(interruptEx);
}
return numResources;
}
public synchronized int takeOne()
{
try
{
while (numResources == 0)
Search WWH ::




Custom Search