Java code explanation with details
I realized that writing tranditional synchronized block or using lock with condition variable may not be cleaner since it will be easy to get it hard to read. N
I realized that writing tranditional synchronized block or using lock with condition variable may not be cleaner since it will be easy to get it hard to read. Nonetheless, the idea behind those solutions would be to add dependencies across different threads given the vlaue of n. The simpler pattern is to use semaphores. The binary semaphore is assigned to the thread that we want to be executed first. For example, we want to execute zero as the first thread so that is going to be created with 1 permit. For the other two threads, we will create will 0 permit so that we can control those from the Zero thread. \n\n```\nclass ZeroEvenOdd {\n    private int n;    \n    private final Semaphore even = new Semaphore(0);\n    private final Semaphore zero = new Semaphore(1);\n    private final Semaphore odd = new Semaphore(0);\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        for (int i = 1 ; i <=n ; i++) {\n            zero.acquire();\n            printNumber.accept(0);\n            if (i % 2 == 0) {\n                even.release();\n            } else {\n                odd.release();\n            }\n        }        \n    }\n\n    public void even(IntConsumer printNumber) throws InterruptedException {\n        for (int i = 2 ; i <=n ; i=i+2) {\n            even.acquire();\n            printNumber.accept(i);\n            zero.release();\n        }        \n    }\n\n    public void odd(IntConsumer printNumber) throws InterruptedException {\n        for (int i = 1 ; i <=n ; i=i+2) {\n            odd.acquire();\n            printNumber.accept(i);\n            zero.release();\n        }    \n    }\n}\n```
[]