import java.util.concurrent.Semaphore; /** * class for philosopher with the strategy of first acquiring a chair in order to eat. */ public class Sittingphilosopher extends Philosopher{ private Semaphore chairs; /** * default constructor * @param leftFork a semaphore that represents the fork on the left-hand side of the philosopher * @param rightFork a semaphore that represents the fork on the right-hand side of the philosopher * @param chairs a semaphore that represents the set of available chairs * @param ID an ID for the philosopher. This should be unique for every philosopher. */ public Sittingphilosopher(Semaphore leftFork, Semaphore rightFork, Semaphore chairs, int ID) { super(leftFork, rightFork, ID); this.chairs = chairs; } /** * run method * stops iff flag stopSimulating is true * tries to pick up a chair, then to pick up both forks (left first) before eating and releases forks and * then the chair fterwards */ @Override public void run() { while (!stopSimulating) { // runs until it receives stop signal try { // think for some time think(); // acquire a chair chairs.acquire(); long time = System.nanoTime() / 1000; // microseconds are precise enough // acquire forks leftFork.acquire(); rightFork.acquire(); waitingTime += (double) (System.nanoTime() /1000 - time); // add waiting time // eat for some time eat(); // release forks leftFork.release(); rightFork.release(); // release one chair chairs.release(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }