[Beats 95.85%] Java solution - easy to understand
Find full solution with test codes:\nhttps://github.com/Freeze777/SDE-Interviewer-Notes/blob/main/LeetCodeJava/src/main/java/leetcode/concurrency/DiningPhilosop
# Find full solution with test codes:\nhttps://github.com/Freeze777/SDE-Interviewer-Notes/blob/main/LeetCodeJava/src/main/java/leetcode/concurrency/DiningPhilosophers.java\n\nI ran the code multiple times to make sure it passes\n\n# Code\n```\npublic class DiningPhilosophers {\n    private final ReentrantLock[] forks;\n\n    public DiningPhilosophers() {\n        forks = new ReentrantLock[5];\n        Arrays.fill(forks, new ReentrantLock());\n    }\n\n    public void wantsToEat(int philosopher,\n                           Runnable pickLeftFork,\n                           Runnable pickRightFork,\n                           Runnable eat,\n                           Runnable putLeftFork,\n                           Runnable putRightFork) throws InterruptedException {\n        var forksRequired = new ArrayList<>(List.of(philosopher, (philosopher + 1) % 5));\n        forksRequired.sort(Integer::compareTo);\n        var firstFork = forksRequired.get(0);\n        var secondFork = forksRequired.get(1);\n        System.out.println(Thread.currentThread().getName() + " wants to eat");\n        while (true) { //philosopher should eat and think alternatively.\n            if (forks[firstFork].tryLock(1, TimeUnit.MILLISECONDS)) {\n                if (forks[secondFork].tryLock(1, TimeUnit.MILLISECONDS)) { //wait is required to avoid deadlock\n                    pickLeftFork.run();\n                    pickRightFork.run();\n                    eat.run();\n                    putRightFork.run();\n                    putLeftFork.run();\n                    System.out.println(Thread.currentThread().getName() + " finished eating");\n                    forks[secondFork].unlock();\n                    forks[firstFork].unlock();\n                    break;\n                } else {\n                    forks[firstFork].unlock();\n                }\n            }\n        }\n    }\n}\n```
['Java']