Java Reference
In-Depth Information
int cookingTime = 0;
while(true)
{
synchronized(buffet)
{
while(!buffet.isEmpty())
{
try
{
System.out.println(“Chef is waiting...”);
buffet.wait();
}catch(InterruptedException e)
{}
}
}
//Bake some pizzas
try
{
System.out.println(“Chef is cooking...”);
cookingTime = (int) (Math.random()*3000);
Thread.sleep(cookingTime);
}catch(InterruptedException e)
{}
if(cookingTime < 1500)
{
buffet.setEmpty(true);
}
else
{
buffet.setEmpty(false);
synchronized(buffet)
{
buffet.notify();
}
}
}
}
}
The following LunchCrowd class is the consumer of the Buffet object. If the
buffet is empty, the lunch crowd waits for the chef to cook some pizzas and
invoke notify(). If the buffet is not empty, the lunch crowd eats for a random
amount of time. If enough pizza is eaten to empty the buffet, the chef is notified.
Search WWH ::




Custom Search