package philosopher2; import src.Chopstick; public class Philosopher implements Runnable { private final Chopstick leftChopstick; private final Chopstick rightChopstick; private final boolean isRightHanded; // Asymmetry flag public Philosopher(Chopstick leftChopstick, Chopstick rightChopstick, boolean isRightHanded) { this.leftChopstick = leftChopstick; this.rightChopstick = rightChopstick; this.isRightHanded = isRightHanded; } @Override public void run() { try { while (true) { think(); if (isRightHanded) { synchronized (rightChopstick) { rightChopstick.pickUp(); synchronized (leftChopstick) { leftChopstick.pickUp(); eat(); leftChopstick.putDown(); } rightChopstick.putDown(); } } else { synchronized (leftChopstick) { leftChopstick.pickUp(); synchronized (rightChopstick) { rightChopstick.pickUp(); eat(); rightChopstick.putDown(); } leftChopstick.putDown(); } } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private void think() { System.out.println(Thread.currentThread().getName() + " is thinking."); } private void eat() { System.out.println(Thread.currentThread().getName() + " is eating."); } }