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