Java | simple solution using semaphore
The idea is very simple here: \n1. Create a semaphore array to represent the forks.\n2. Philosophers can only eat when the two forks are ready. Otherwise they w
The idea is very simple here: \n1. Create a semaphore array to represent the forks.\n2. Philosophers can only eat when the two forks are ready. Otherwise they will wait.\n3. After the philosopher eats, he put both forks at the same time.\n\nNotice that we should prevent the dead lock(5 philosophers put up forks together), we need a semaphore to limit the number of philosopher who pick up the forks.\n\n```\nclass DiningPhilosophers {\n    Semaphore[] forks = new Semaphore[5];\n    Semaphore eating = new Semaphore(4);\n    public DiningPhilosophers() {\n        for(int i=0;i<5;i++){\n            forks[i] = new Semaphore(1);\n        }\n    }\n\n    // call the run() method of any runnable to execute its code\n    public void wantsToEat(int i,\n                           Runnable pickLeftFork,\n                           Runnable pickRightFork,\n                           Runnable eat,\n                           Runnable putLeftFork,\n                           Runnable putRightFork) throws InterruptedException {\n        eating.acquire();\n        forks[i].acquire();\n        forks[(i+1)%5].acquire();\n        pickLeftFork.run();\n        pickRightFork.run();\n        \n        eat.run();\n        \n        putLeftFork.run();\n        putRightFork.run();\n        forks[i].release();\n        forks[(i+1)%5].release();\n        eating.release();\n    }\n}\n```
['Java']