[Java] wait() and notifyAll() solution 7 ms | Clean Readable Code
\n\nclass ZeroEvenOdd {\n\tprivate int n;\n\n\tpublic ZeroEvenOdd(int n) {\n\t\tthis.n = n;\n\t}\n\n\tprivate volatile boolean hasZeroRun = false;\n\tprivate vo
```\n\nclass ZeroEvenOdd {\n\tprivate int n;\n\n\tpublic ZeroEvenOdd(int n) {\n\t\tthis.n = n;\n\t}\n\n\tprivate volatile boolean hasZeroRun = false;\n\tprivate volatile int currentNumber = 1;\n\tprivate final Object oddEvenMonitor = new Object();\n\n\t// printNumber.accept(x) outputs "x", where x is an integer.\n\tpublic void zero(IntConsumer printNumber) throws InterruptedException {\n\t\twhile (currentNumber <= n) {\n\t\t\tsynchronized (oddEvenMonitor) {\n\t\t\t\twhile (hasZeroRun && currentNumber <= n) {\n\t\t\t\t\toddEvenMonitor.wait();\n\t\t\t\t}\n\n\t\t\t\tif (currentNumber <= n) {\n\t\t\t\t\tprintNumber.accept(0);\n\t\t\t\t\thasZeroRun = true;\n\t\t\t\t}\n\n\t\t\t\toddEvenMonitor.notifyAll();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void even(IntConsumer printNumber) throws InterruptedException {\n\t\twhile (currentNumber <= n) {\n\t\t\tsynchronized (oddEvenMonitor) {\n\t\t\t\twhile ((!isEven(currentNumber) || !hasZeroRun) && currentNumber <= n) {\n\t\t\t\t\toddEvenMonitor.wait();\n\t\t\t\t}\n\t\t\t\tif (currentNumber <= n) {\n\t\t\t\t\tprintNumber.accept(currentNumber);\n\t\t\t\t\tcurrentNumber++;\n\t\t\t\t\thasZeroRun = false;\n\t\t\t\t}\n\n\t\t\t\toddEvenMonitor.notifyAll();\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic void odd(IntConsumer printNumber) throws InterruptedException {\n\t\twhile (currentNumber <= n) {\n\t\t\tsynchronized (oddEvenMonitor) {\n\t\t\t\twhile ((!isOdd(currentNumber) || !hasZeroRun) && currentNumber <= n) {\n\t\t\t\t\toddEvenMonitor.wait();\n\t\t\t\t}\n\n\t\t\t\tif (currentNumber <= n) {\n\t\t\t\t\tprintNumber.accept(currentNumber);\n\t\t\t\t\tcurrentNumber++;\n\t\t\t\t\thasZeroRun = false;\n\t\t\t\t}\n\n\t\t\t\toddEvenMonitor.notifyAll();\n\t\t\t}\n\t\t}\n\n\t}\n\n\tprivate boolean isOdd(int currentNumber) {\n\t\treturn currentNumber % 2 != 0;\n\t}\n\n\tprivate boolean isEven(int currentNumber) {\n\t\treturn currentNumber % 2 == 0;\n\t}\n}\n\n\n```
[]