Java solution using wait() and notifyAll()
A lot of solutions on here are using busy waits or sleeps - which are only slightly better. That is essentially a \'fail\' w.r.t. this question on threads. Here
A lot of solutions on here are using busy waits or sleeps - which are only slightly better. That is essentially a \'fail\' w.r.t. this question on threads. Here\'s the solution I believe an interviewer would be looking for that uses wait() and notifyAll() with a liveness check inside a synchronized block. The locking object instance used in this code is the instance of Foo. I.e. \'this\'. Using wait() and notifyAll() means that the processors aren\'t spinning and unnecessarily burning through compute power! \n\nAlso - notice that the thread coordination logic happens inside a synchronized block. Without that, there is no guarantee that the JVM memory model will communicate the state of the variables between threads. Always, put this kind of thread-coordination logic inside synchronized blocks. \n\nAlso - the Java seed code for this question is incorrectly using the Runnable interface. You never call run() on a runnable! That is for the JVM to call in a new thread when it is started. \n\n```\nclass Foo {\n    private boolean firstDone = false;\n    private boolean secondDone = false;\n    \n    public Foo() {\n        \n    }\n\n    public void first(Runnable printFirst) throws InterruptedException {\n        synchronized(this) {\n            // printFirst.run() outputs "first". Do not change or remove this line.\n            printFirst.run();\n            firstDone = true;\n            this.notifyAll();\n        }\n    }\n\n    public void second(Runnable printSecond) throws InterruptedException {\n        synchronized(this) {\n            while (!firstDone) {\n                this.wait();\n            }\n            // printSecond.run() outputs "second". Do not change or remove this line.\n            printSecond.run();\n            this.secondDone = true;\n            this.notifyAll();\n        }\n    }\n\n    public void third(Runnable printThird) throws InterruptedException {\n        synchronized(this) {\n            while (!secondDone) {\n                this.wait();\n            }\n            // printThird.run() outputs "third". Do not change or remove this line.\n            printThird.run();\n            this.notifyAll();\n        }\n    }\n}\n```\n
[]