import java.util.concurrent.Semaphore; public class DiningPhilosophers { static Fork[] forks = new Fork[6]; static Philosopher[] philosophers = new Philosopher[6]; public static void main(String[] args) { for(int i = 0; i < 6; i++) { forks[i] = new Fork(); } for(int i = 0; i < 6; i++) { philosophers[i] = new Philosopher("P" + i, forks[i], forks[(i + 1) % 6]); } for(int i = 0; i < 6; i++) { philosophers[i].start(); } for(int i = 0; i < 6; i++) { try { philosophers[i].join(); } catch(InterruptedException e) { } } } static class Fork { Semaphore fork_semaphore = new Semaphore(1); void take_fork() { try { fork_semaphore.acquire(); } catch (InterruptedException e) { } } void put_back_fork() { fork_semaphore.release(); } } static class Philosopher extends Thread { String name; Fork left_fork; Fork right_fork; Philosopher(String _name, Fork _left, Fork _right) { name = _name; left_fork = _left; right_fork = _right; } @Override public void run() { left_fork.take_fork(); right_fork.take_fork(); eat(); left_fork.put_back_fork(); right_fork.put_back_fork(); think(); } void eat() { System.out.println(name + " is eating!"); try { Thread.sleep(100); } catch (InterruptedException e) { } } void think() { System.out.println(name + " is thinking!"); } } } /// 1 2 3 4 5 6