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