import java.util.concurrent.Semaphore; /** * class for a philosopher that picks up the left fork first and then the right fork * otherwise identical to NaivePhilosopher */ public class InvertedPhilosopher extends Philosopher{ /** * 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 ID an ID for the philosopher. This should be unique for every philosopher. */ public InvertedPhilosopher(Semaphore leftFork, Semaphore rightFork, int ID) { super(leftFork, rightFork, ID); } /** * run method * stops iff flag stopSimulating is true * tries to pick up both forks (right first) before eating and releases forks afterwards */ @Override public void run() { while (!stopSimulating) { // runs until it receives stop signal try { think(); // thinks long time = System.nanoTime() / 1000; // microseconds are precise enough rightFork.acquire(); // acquire both forks (right first!) leftFork.acquire(); waitingTime += (double) (System.nanoTime() /1000 - time); // add waiting time eat(); // eats leftFork.release(); // release both forks rightFork.release(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }