[Java] State machine solution with synchronized
So here we use state machine with 4 stages\n0 - printing zero\n1 - printing odd\n2 - printing zero\n3 - printing even -> and then again 0 in a cycle\n\nWe synch
So here we use state machine with 4 stages\n0 - printing zero\n1 - printing odd\n2 - printing zero\n3 - printing even -> and then again 0 in a cycle\n\nWe synchronize 3 threads using class based lock and wait until proper stage for each thread, then accept number and notify others to continue.\n\n```\nclass ZeroEvenOdd {\n    private int stage = 0;\n    private int n;\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 synchronized void zero(IntConsumer printNumber) throws InterruptedException {\n        for (int current = 1; current <= n; current++) {\n            while (stage != 0 && stage != 2) {\n                wait();\n            } \n            printNumber.accept(0);\n            stage++;\n            notifyAll();\n        }\n    }\n\n    public synchronized void even(IntConsumer printNumber) throws InterruptedException {\n        for (int current = 2; current <= n; current += 2) {\n            while (stage != 3) {\n                wait();\n            }   \n            printNumber.accept(current);\n            stage = 0;\n            notifyAll();\n        }\n    }\n\n    public synchronized void odd(IntConsumer printNumber) throws InterruptedException {\n        for (int current = 1; current <= n; current += 2) {\n            while (stage != 1) {\n                wait();\n            }   \n            printNumber.accept(current);\n            stage++;\n            notifyAll();\n        }\n    }\n}\n```\n
[]