import java.util.concurrent.Semaphore; /** * class for philosopher with naive strategy. */ public class NaivePhilosopher 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 NaivePhilosopher(Semaphore leftFork, Semaphore rightFork, int ID) { super(leftFork, rightFork, ID); } /** * run method * stops iff flag stopSimulating is true * tries to pick up both forks (left first) before eating and releases forks afterwards */ @Override public void run() { while (!stopSimulating) { // runs until it receives stop signal try { think(); // think // track waiting time long time = System.nanoTime() / 1000; // microseconds are precise enough leftFork.acquire(); // acquire both forks (left first) // System.out.println("Philosopher "+ ID + " acquired left fork."); //Thread.sleep(10); // uncomment this to see blocking rightFork.acquire(); // System.out.println("Philosopher "+ ID + " acquired right fork."); waitingTime += (double) (System.nanoTime() /1000 - time); // add waiting time eat(); // eat leftFork.release(); // release both forks // System.out.println("Philosopher "+ ID + " released left fork."); rightFork.release(); // System.out.println("Philosopher "+ ID + " released left fork."); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }