Java Solution using Semaphores | 7 ms faster than 99.84% | 38.2 MB less than 36.73%
The Semaphores define the order in which zero, even and odd are printed. I use a counter variable to ensure that only 2n numbers are printed. This solution woul
The Semaphores define the order in which zero, even and odd are printed. I use a counter variable to ensure that only 2n numbers are printed. This solution would also make it easier to change the length of the sequence since only the numLeft variable would need to be changed.\n```\nimport java.util.concurrent.Semaphore;\n\nclass ZeroEvenOdd {\n    private int n;\n\n    public ZeroEvenOdd(int n) {\n        this.n = n;\n        numLeft = n * 2;\n    }\n\n    private final Semaphore zeroSemaphore = new Semaphore(1);\n    private final Semaphore evenSemaphore = new Semaphore(0);\n    private final Semaphore oddSemaphore = new Semaphore(0);\n\n    private int even = 2;\n    private int odd = 1;\n    private int zeroCount = 0;\n\n    private int numLeft;\n\n    // printNumber.accept(x) outputs "x", where x is an integer.\n    public void zero(IntConsumer printNumber) throws InterruptedException {\n        while (true) {\n            zeroSemaphore.acquire();\n            if (numLeft == 0) {\n                oddSemaphore.release();\n                evenSemaphore.release();\n                break;\n            }\n            printNumber.accept(0);\n            numLeft--;\n            if (++zeroCount % 2 == 1) {\n                oddSemaphore.release();\n            } else {\n                evenSemaphore.release();\n            }\n        }\n    }\n\n    public void even(IntConsumer printNumber) throws InterruptedException {\n        while (true) {\n            evenSemaphore.acquire();\n            if (numLeft == 0) {\n                zeroSemaphore.release();\n                break;\n            }\n            printNumber.accept(even);\n            even += 2;\n            numLeft--;\n            zeroSemaphore.release();\n        }\n    }\n\n    public void odd(IntConsumer printNumber) throws InterruptedException {\n        while (true) {\n            oddSemaphore.acquire();\n            if (numLeft == 0) {\n                zeroSemaphore.release();\n                break;\n            }\n            printNumber.accept(odd);\n            odd += 2;\n            numLeft--;\n            zeroSemaphore.release();\n        }\n    }\n}\n```
['Java']