package com.greenorange.promotion.homework;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DiningPhilosophers {
    private final Lock[] forks = new Lock[5];

    public DiningPhilosophers() {
        for (int i = 0; i < 5; i++) forks[i] = new ReentrantLock();
    }

    public void philosopher(int id) {
        try {
            think(id);
            if (id % 2 == 0) { forks[(id + 1) % 5].lock(); forks[id].lock(); }
            else { forks[id].lock(); forks[(id + 1) % 5].lock(); }
            eat(id);
        } finally { forks[id].unlock(); forks[(id + 1) % 5].unlock(); }
    }

    private void think(int id) { System.out.println("哲学家 " + id + " 在思考..."); }
    private void eat(int id) { System.out.println("哲学家 " + id + " 在吃饭..."); }

    public static void main(String[] args) {
        DiningPhilosophers dp = new DiningPhilosophers();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> dp.philosopher(finalI)).start();
        }
    }
}
