[Java] Use Semphore (the test case had bug)
The code is as following. But it may fail to pass the test case. I think the test case has a bug in it.\n\nHere is one failed test output:\n[[2,1,1],[2,2,1],[0,
The code is as following. But it may fail to pass the test case. I think the test case has a bug in it.\n\nHere is one failed test output:\n[[2,1,1],[2,2,1],[0,1,1],[0,2,1],[0,0,3],[0,1,2],[0,2,2],[2,0,3],[2,1,2],[2,2,2],[1,1,1],[1,2,1],[4,1,1],[4,2,1],[4,0,3],[4,1,2],[4,2,2],[1,0,3],[1,1,2],[1,2,2]]\n\nAnd the expected output:\n[[3,2,1],[3,1,1],[3,0,3],[3,1,2],[3,2,2],[4,2,1],[4,1,1],[2,2,1],[2,1,1],[1,2,1],[2,0,3],[2,1,2],[2,2,2],[4,0,3],[4,1,2],[4,2,2],[1,1,1],[1,0,3],[1,1,2],[1,2,2],[0,1,1],[0,2,1],[0,0,3],[0,1,2],[0,2,2]]\n\nObviously, some outputs were lost. I guess the outputs collect code in the test case has bugs.\n\n```\nclass DiningPhilosophers {\n    private int num;\n    private Semaphore[] forkSemaphores;\n    private Semaphore gateSemaphore;\n\n    DiningPhilosophers() {\n        this(5);\n    }\n\n    DiningPhilosophers(int num) {\n        this.num = num;\n        forkSemaphores = new Semaphore[num];\n        for (int i = 0; i < num; i++) {\n            forkSemaphores[i] = new Semaphore(1, true);\n        }\n        gateSemaphore = new Semaphore(num - 1, true);\n    }\n\n    public void wantsToEat(int philosopher, Runnable pickLeftFork, Runnable pickRightFork,\n            Runnable eat, Runnable putLeftFork, Runnable putRightFork) throws InterruptedException {\n        gateSemaphore.acquire();\n\n        Semaphore leftSemaphore = forkSemaphores[philosopher];\n        Semaphore rightSemaphore = forkSemaphores[(philosopher + 4) % num];  // clockwise\n\n        // the philosopher should get the available fork first and then wait for another one\n        boolean gotRightFork = rightSemaphore.tryAcquire();\n        leftSemaphore.acquire();\n        if (!gotRightFork) {\n            rightSemaphore.acquire();\n        }\n\n        pickLeftFork.run();\n        pickRightFork.run();\n\n        eat.run();\n\n        putLeftFork.run();\n        putRightFork.run();\n\n        leftSemaphore.release();\n        rightSemaphore.release();\n\n        gateSemaphore.release();\n    }\n}\n```
[]