public boolean chopsticksFree()
{
return !host.getChopstick(index) &&
!host.getChopstick((index+1)%host.getCount());
}
public void run()
{
while(true)
{
grabChopsticks();
eat();
think();
}
}
private synchronized void grabChopsticks() /**临界区函数,确保哲学家在没有筷子或筷子不够时思考,满足条件后才就餐*/
{
while( !chopsticksFree())
{
try
{
wait();
}
catch( InterruptedException e){}
}
takeChopsticks();
notifyAll();
}
private void takeChopsticks()
{
setLeftChopstick( true );
setRightChopstick( true );
setEat(true);
host.dumpStatus();
}
责任编辑:小草