Java Reference
In-Depth Information
between successive (attempted) increments of the resource level, so that it does
not produce so quickly that it is always at maximum (or, very briefl y, one below
class Producer extends Thread
private Resource item;
public Producer(Resource resource)
item = resource;
public void run()
int pause;
int newLevel;
//Add 1 to level and return new level…
newLevel = item.addOne();
"<Producer> New level: " + newLevel);
pause = (int)(Math.random() * 5000);
//'Sleep' for 0-5 seconds…
catch (InterruptedException interruptEx)
}while (true);
Just as a factory may not produce more than it can either sell or store, so the
producer normally has some maximum resource level beyond which it must not
produce. In this simple example, the resource level will not be allowed to exceed 5.
Once the resource level has reached 5, production must be suspended. This is done
from method addOne by calling wait from within a loop that continuously checks
whether the resource level is still at maximum. The calling of wait suspends the
Producer thread and releases the lock on the shared resource level variable, allow-
ing any ConsumerClient to obtain it. When the resource level is below the maxi-
mum, addOne increments the level and then calls method notify to 'wake up' any
waiting ConsumerClient thread.
Search WWH ::

Custom Search