Skip to content

Instantly share code, notes, and snippets.

@Wilfred
Created May 4, 2009 09:40
Show Gist options
  • Save Wilfred/106394 to your computer and use it in GitHub Desktop.
Save Wilfred/106394 to your computer and use it in GitHub Desktop.
class DiningPhilosophers {
public static void main(String[] args) {
Fork[] forks = new Fork[5];
for (int i=0; i<forks.length; i++) {
forks[i] = new Fork();
}
Philosopher p1 = new Philosopher(1,forks[0],forks[1]);
Philosopher p2 = new Philosopher(2,forks[1],forks[2]);
Philosopher p3 = new Philosopher(3,forks[2],forks[3]);
Philosopher p4 = new Philosopher(4,forks[3],forks[4]);
Philosopher p5 = new Philosopher(5,forks[4],forks[0]);
p1.start();
p2.start();
p3.start();
p4.start();
p5.start();
}
}
class Philosopher extends Thread {
private Fork l,r;
private int num;
public void run() {
while(true) {
eat();
}
}
void eat() {
synchronized(l) {
synchronized(r) {
System.out.printf("Philopher %d eating.\n",num);
System.out.printf("Current time is %d\n",
System.currentTimeMillis());
}
}
}
Philosopher(int num, Fork l, Fork r) {
this.num = num;
this.l = l;
this.r = r;
}
}
class Fork {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment