After changing the if
to a while
in the run
method of philosopher, try updating the Forks
functions for take and return as follows:
public synchronized void returnFork() throws InterruptedException
{
available = true;
this.notifyAll();
}
public synchronized void takeFork() throws InterruptedException
{
while(!available){
this.wait();
}
available = false;
}
I then made a couple of tweaks in the run
method of philosophers as follows:
if (!hasBothForks){
print("is hungry");
print( "checks if forks are free");
}
if(right.isFree() == true && left.isFree() == true && hasBothForks == false)
{
print("is grabbing forks");
right.takeFork();
left.takeFork();
hasBothForks = true;
} // end if
else if(hasBothForks == true)
{
print("is eating");
Thread.sleep(2000);
print("is putting down left fork");
left.returnFork();
print("is putting down right fork");
right.returnFork();
print("is finished eating");
hasBothForks = false;
} // end if
else if((right.isFree() == false || left.isFree() == false) && hasBothForks == false)
{
print("is thinking");
Thread.sleep(2000);
} // end if
With these two sets of changes I see the output flow much better. Still not sure if it's exactly what you want though.