Simple java solution with semaphores
The idea is really simple. We will be using three semaphores, one for thread. Only one thread will be allowed to run at a time.\n\nThe first one to run should b
The idea is really simple. We will be using three semaphores, one for thread. Only one thread will be allowed to run at a time.\n\nThe first one to run should be zero(), meaning its semaphore should be set to 1 (so it can acquire it). \nEven() and Odd() shouldn\'t be executed first, so we\'ll set their semaphores to 0, meaning they will be put to sleep if they happen to run before zero().\n\nThe problem is... how we alternate between printing odd and even numbers? \nWell, we can simply let zero() decide.\n\nHow do odd() and even() work?\nThey wait for their turn by attempting to acquire their lock, then print the next number and release zero() so it can go again\n\n```\nimport java.util.concurrent.Semaphore;\n\nclass ZeroEvenOdd {\n    private int n;\n    \n    private final Semaphore canZero = new Semaphore(1); // can print zero immediately\n    private final Semaphore canOdd = new Semaphore(0); // can\'t print an odd number at first\n    private final Semaphore canEven = new Semaphore(0); // can\'t print an even number either\n    \n    public ZeroEvenOdd(int n) {\n        this.n = n;\n    }\n\n    // printNumber.accept(x) outputs "x", where x is an integer.\n    public void zero(IntConsumer printNumber) throws InterruptedException {\n        boolean isEvenTurn = false; // An odd number should be printed first\n        \n        for (int i = 0; i < n; i++) {\n            canZero.acquire();\n            printNumber.accept(0);\n            \n            if (isEvenTurn)\n                canEven.release();\n            else\n                canOdd.release();\n            \n            isEvenTurn = !isEvenTurn; // change turn\n        }\n    }\n\n    public void even(IntConsumer printNumber) throws InterruptedException {\n        for (int i = 2; i <= n; i += 2) {\n            canEven.acquire();\n            printNumber.accept(i);\n            canZero.release();\n        }\n    }\n\n    public void odd(IntConsumer printNumber) throws InterruptedException {\n        for (int i = 1; i <= n; i += 2) {\n            canOdd.acquire();\n            printNumber.accept(i);\n            canZero.release();\n        }\n    }\n}\n```
['Java']