thinkinghungryeating
| Philosopher | State | Meals | Time waiting |
|---|
Dining philosophers sit around a table with a fork between each pair of neighbours. Each one thinks, gets hungry, picks up the forks on both sides, eats and puts them back. If they all pick up the left fork first, they can end up each holding one fork and waiting forever for the other. My solution: the odd-numbered philosophers pick up the right fork first. Switch to the naive way and click “Everyone gets hungry at once”: all the forks go back on the table and everyone reaches for one at the same moment.
| Philosopher | State | Meals | Time waiting |
|---|
/**
* @author Mihailo Despotovic
* @since Aug 24, 2005 4:37:44 PM
*/
public class Dinner
{
public static void main(String[] args)
{
// the dimension of the problem
int numForks = 5;
// create forks
Fork[] forks = new Fork[numForks];
for(int i=0; i<numForks; i++)
forks[i] = new Fork();
// create philosophers and start them
for(int i=0; i<numForks; i++)
{
// decide which forks go to this one
Fork left = forks[i];
Fork right = forks[(i+1)%numForks];
// create him
Philosopher p;
if(i % 2 == 0)
p = new Philosopher("" + i, left, right);
else
p = new Philosopher("" + i, right, left);
// let him start
new Thread(p).start();
}
}
}
/**
* @author Mihailo Despotovic
* @since Aug 24, 2005 4:28:36 PM
*/
public class Fork
{
private boolean free = true;
public synchronized void pickUp()
{
// spinwait
while(!free)
{
try
{
wait();
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
// execute
free = false;
}
public synchronized void putDown()
{
free = true;
notify();
}
}
/**
* @author Mihailo Despotovic
* @since Aug 24, 2005 4:30:38 PM
*/
public class Philosopher implements Runnable
{
private String name;
private Fork left, right;
public Philosopher(String name, Fork left, Fork right)
{
this.name = name;
this.left = left;
this.right = right;
}
public void run()
{
// forever...
while(true)
{
// think a bit...
System.out.println(name + " is thinking...");
try
{
Thread.sleep((int)(Math.random() * 5000));
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
// pick up
System.out.println(name + " is picking up his left fork...");
left.pickUp();
System.out.println(name + " is picking up his right fork...");
right.pickUp();
// eating...
System.out.println(name + " is eating...");
try
{
Thread.sleep((int)(Math.random() * 5000));
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
// put down
System.out.println(name + " is putting down his left fork...");
left.putDown();
System.out.println(name + " is picking up his right fork...");
right.putDown();
}
}
}