Intuitive Java Solution With Explanation
Idea\nUse Guarded Block\nhttps://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html\n\nBasically, adding synchronized keyword to all the metho
**Idea**\nUse `Guarded Block`\nhttps://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html\n\nBasically, adding `synchronized` keyword to all the methods will require any thread to acquire intrisic lock of the object of `Foo` (which is used by all the three thread below).\nNow on this lock, we can conditionally block the threads based on current `counter` value. Only unblock the thread for which the condition that it was waiting for is met and rest of the threads will be blocked (their execution is suspended by the `wait()` call). \n\n```\nclass Foo {\n    int counter = 1;\n    public Foo() {\n        \n    }\n\n    public synchronized void first(Runnable printFirst) throws InterruptedException {\n        while(counter != 1){\n            wait();\n        }\n        // printFirst.run() outputs "first". Do not change or remove this line.\n        printFirst.run();\n        ++counter;\n        notifyAll();\n    }\n\n    public synchronized void second(Runnable printSecond) throws InterruptedException {\n        while(counter != 2){\n            wait();\n        }\n        // printSecond.run() outputs "second". Do not change or remove this line.\n        printSecond.run();\n        ++counter;\n        notifyAll();\n    }\n\n    public synchronized void third(Runnable printThird) throws InterruptedException {\n        while(counter != 3){\n            wait();\n        }\n        // printThird.run() outputs "third". Do not change or remove this line.\n        printThird.run();\n        ++counter;\n        notifyAll();\n    }\n}\n```
[]