import java.util.concurrent.Semaphore; public class DiningPhilosophers { // Number of philosophers private static final int NUM_PHILOSOPHERS = 5; static class Philosopher implements Runnable { private final int id; private final Semaphore leftFork; private final Semaphore rightFork; public Philosopher(int id, Semaphore leftFork, Semaphore rightFork) { this.id = id; this.leftFork = leftFork; this.rightFork = rightFork; } @Override public void run() { try { while (true) { think(); pickUpForks(); eat(); putDownForks(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private void think() throws InterruptedException { System.out.println("Philosopher " + id + " is thinking."); Thread.sleep((long) (Math.random() * 1000)); } private void eat() throws InterruptedException { System.out.println("Philosopher " + id + " is eating."); Thread.sleep((long) (Math.random() * 1000)); } private void pickUpForks() throws InterruptedException { leftFork.acquire(); rightFork.acquire(); } private void putDownForks() { leftFork.release(); rightFork.release(); } } public static void main(String[] args) { Semaphore[] forks = new Semaphore[NUM_PHILOSOPHERS]; for (int i = 0; i < NUM_PHILOSOPHERS; i++) { forks[i] = new Semaphore(1); } Philosopher[] philosophers = new Philosopher[NUM_PHILOSOPHERS]; for (int i = 0; i < NUM_PHILOSOPHERS; i++) { Semaphore leftFork = forks[i]; Semaphore rightFork = forks[(i + 1) % NUM_PHILOSOPHERS]; philosophers[i] = new Philosopher(i, leftFork, rightFork); new Thread(philosophers[i], "Philosopher " + i).start(); } } }