[Java] Basic semaphore solution - 4ms, 35.8MB [Updated]
Leetcode fixed the bug where you could:\nYou\'ll notice that you dont need the "printZero" thread. You could just print a zero before you print an odd or an eve
Leetcode fixed the bug where you could:\n*You\'ll notice that you dont need the "printZero" thread. You could just print a zero before you print an odd or an even number.*\nSo you can\'t do that anymore...\n\nNon-shared variables (local to one thread) don\'t need synchronization.\n\nUpvote and check out my other concurrency solutions.\n```\nimport java.util.concurrent.*;\nclass ZeroEvenOdd {\n    int n;\n    \n    Semaphore semaphoreEven, semaphoreOdd, semaphoreZero;\n    \n    public ZeroEvenOdd(int n) {\n        this.n = n;\n        \n        semaphoreZero = new Semaphore(1);\n        semaphoreEven = new Semaphore(0);\n        semaphoreOdd = new Semaphore(0);\n    }\n\n    // printNumber.accept(x) outputs "x", where x is an integer.\n    public void zero(IntConsumer printNumber) throws InterruptedException {\n        int numTimes = this.n;\n        boolean printOdd = true;\n        \n        for(int i = 0; i < numTimes; i++){\n            semaphoreZero.acquire();\n\t\t\t\n            printNumber.accept(0);\n\n            //print the next number\n            if(printOdd)\n                semaphoreOdd.release();\n            else\n                semaphoreEven.release();\n            \n            printOdd = !printOdd;   //flip it!\n        }\n    }\n\n    public void even(IntConsumer printNumber) throws InterruptedException {\n        int numTimes = this.n / 2;\n        \n        int nextEvenNum = 2;\n        for(int i = 0; i < numTimes; i++){\n            semaphoreEven.acquire();\n            \n            printNumber.accept(nextEvenNum);\n            nextEvenNum += 2;\n            \n            semaphoreZero.release();\n        }\n    }\n\n    public void odd(IntConsumer printNumber) throws InterruptedException {\n        int numTimes = (int)Math.ceil((double)this.n / 2);\n        \n        int nextOdd = 1;\n        for(int i = 0; i < numTimes; i++){\n            semaphoreOdd.acquire();\n            \n            printNumber.accept(nextOdd);\n            nextOdd += 2;\n            \n            semaphoreZero.release();\n        }\n    }\n}\n```
[]