The five philosophers
Posted Tue, 20 Nov 2007 09:54:00 GMT
Here’s my little implementation of the five philosophers problem.
The chopstick:
package philosophers;
public class Chopstick {
private int number;
public Chopstick(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
The philosopher:
package philosophers;
public class Philosopher implements Runnable {
private int number;
private Chopstick leftChopstick;
private Chopstick rightChopstick;
public Philosopher(int number, Chopstick leftChopstick,
Chopstick rightChopstick) {
this.number = number;
this.leftChopstick = leftChopstick;
this.rightChopstick = rightChopstick;
}
private void eat(int time) {
synchronized (leftChopstick) {
System.out.println("Philosopher " + this.number
+ " took chopstick " + leftChopstick.getNumber()
+ " from the left.");
synchronized (rightChopstick) {
System.out.println("Philosopher " + this.number
+ " took chopstick " + rightChopstick.getNumber()
+ " from the right.");
try {
System.out.println("Philosopher " + this.number
+ " is eating...");
Thread.sleep(time);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
private void think(int time) {
try {
System.out.println("Philosopher " + this.number + " is thinking...");
Thread.sleep(time);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void run() {
while (true) {
think(1);
eat(1);
}
}
}
And, bringing them all together, the Table:
package philosophers;
public class Table {
/**
* Chopstick 0 is on the left of phylosopher 0
*/
private Chopstick[] chopsticks;
private Philosopher[] philosophers;
public void build(int numberOfSeats) {
for (int i = 0; i < numberOfSeats; i++) {
chopsticks[i] = new Chopstick(i);
}
for (int i = 0; i < numberOfSeats; i++) {
philosophers[i] = new Philosopher(i, chopsticks[i],
chopsticks[i < numberOfSeats - 1 ? i + 1 : 0]);
}
}
public Table(int numberOfSeats) {
chopsticks = new Chopstick[numberOfSeats];
philosophers = new Philosopher[numberOfSeats];
build(numberOfSeats);
}
public void start() {
System.out.println("Chopstick 0 is on the left of philosopher 0");
for (Philosopher philosopher : philosophers) {
new Thread(philosopher).start();
}
}
public static void main (String[] args) {
new Table(5).start();
}
}
Deadlocks pretty quickly with the numbers as they are here.
