/** * A philosopher who thinks, gets hungry and eats with two forks. * * @author Franck van Breugel */ public abstract class Philosopher extends Thread { private int id; private static final int THINKING = 0; private static final int HUNGRY = 1; private static final int EATING = 2; private static int[] state = { 0, 0, 0, 0, 0 }; /** * Initialize this philosopher with the given id. * * @param id the id of this philosopher. */ public Philosopher(int id) { this.id = id; } /** * Life of this philosopher. */ public void run() { while (true) { // think // becomes hungry synchronized (this) { Philosopher.state[this.id] = Philosopher.HUNGRY; while (Philosopher.state[(this.id - 1) % Philosopher.state.length] == Philosopher.EATING || Philosopher.state[(this.id + 1) % Philosopher.state.length] == Philosopher.EATING) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Philosopher.state[this.id] = Philosopher.EATING; } // eat synchronized (this) { Philosopher.state[this.id] = Philosopher.THINKING; if (Philosopher.state[(this.id - 1) % Philosopher.state.length] == Philosopher.HUNGRY || Philosopher.state[(this.id + 1) % Philosopher.state.length] == Philosopher.HUNGRY) { this.notifyAll(); } } } } }