The simplest Java solution ever
Obviously, the task can be solved with single synchronized block and invocking provided methods in right order like the following:\n\n\nclass DiningPhilosophers
Obviously, the task can be solved with single synchronized block and invocking provided methods in right order like the following:\n\n```\nclass DiningPhilosophers {\n\n    public DiningPhilosophers() {\n        \n    }\n\n    // call the run() method of any runnable to execute its code\n    public void wantsToEat(int p,\n                           Runnable pickLeftFork,\n                           Runnable pickRightFork,\n                           Runnable eat,\n                           Runnable putLeftFork,\n                           Runnable putRightFork) throws InterruptedException {\n        \n        synchronized(this) {\n            pickLeftFork.run();\n            pickRightFork.run();\n            eat.run();\n            putLeftFork.run();\n            putRightFork.run();\n        }\n    }\n}\n```\n\n**Although this code is accepted, that is not how the task is supposed to be solved**. Hene the following implementation is better from at least of education/practice point of view:\n\n```\nclass DiningPhilosophers {\n    private int n = 5;\n    private ReentrantLock[] forks = new ReentrantLock[n];\n\n    public DiningPhilosophers() {\n        for(int i = 0; i<n; i++) {\n            forks[i] = new ReentrantLock();\n        }\n    }\n\n    // call the run() method of any runnable to execute its code\n    public void wantsToEat(int p,\n                           Runnable pickLeftFork,\n                           Runnable pickRightFork,\n                           Runnable eat,\n                           Runnable putLeftFork,\n                           Runnable putRightFork) throws InterruptedException {\n        \n        int left = p;\n        int right = p==0 ? n-1 : p-1;\n        while(true) {\n            if(forks[left].tryLock()) {\n               pickLeftFork.run();\n               if(forks[right].tryLock()) {\n                   pickRightFork.run();\n                   eat.run();\n                   putLeftFork.run();\n                   putRightFork.run();\n                   forks[left].unlock();\n                   forks[right].unlock();\n                   break;\n               } else {\n                  putLeftFork.run();\n                  forks[left].unlock();        \n               }\n            }\n            Thread.sleep(1);\n        }\n      \n    }\n}\n```\n\nThe algorythms is simple:\n1. Try to pick left fork.\n2. If yes - try to pick right fork, else go to point 1.\n3. If yes - eat, else go to point 1.
[]