/** * A table with forks. At any time, at most all but one seat can be taken. * * @author Franck van Breugel */ public class Table { private int size; private boolean[] pickedUp; private int empty; // number of seats that are empty /** * Initializes this empty table. * * @param size the size of this table. */ public Table(int size) { this.size = size; this.empty = size; this.pickedUp = new boolean[size]; // all false } /** * Sit down at this table. */ public synchronized void sitDown() { while (this.empty <= 1) { try { this.wait(); } catch (InterruptedException e) {} } // sits down this.empty--; } /** * Stand up from this table. */ public synchronized void standUp() { this.empty++; this.notifyAll(); } /** * Pick up the fork from this table with the given id. * * @param id id of the fork. */ public synchronized void pickUp(int id) { while (this.pickedUp[id % this.size]) { try { this.wait(); } catch (InterruptedException e) {} } this.pickedUp[id % this.size] = true; } /** * Put down the fork on the table with the given id. * * @param id id of the fork. */ public synchronized void putDown(int id) { this.pickedUp[id % this.size] = false; this.notifyAll(); } }