Java Solution beats 100% time and space
Make each thread wait on a mutex using the state of a counter.\n\nclass FooBar {\n    private int n;    \n    volatile int ctr;\n    \n    Object mutex;\n    \n
Make each thread wait on a mutex using the state of a counter.\n```\nclass FooBar {\n    private int n;    \n    volatile int ctr;\n    \n    Object mutex;\n    \n    public FooBar(int n) {\n        this.n = n;\n        ctr=1;\n        \n        mutex = new Object();\n    }\n\n    public void foo(Runnable printFoo) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            \n            synchronized(mutex)\n            {\n                while(ctr%2==0)\n                    mutex.wait();\n                \n                // printFoo.run() outputs "foo". Do not change or remove this line.\n                printFoo.run();\n\n                ctr++;\n                mutex.notifyAll();\n            }\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            \n            synchronized(mutex)\n            {\n                while(ctr%2==1)\n                    mutex.wait();\n            \n                // printBar.run() outputs "bar". Do not change or remove this line.\n                printBar.run();\n\n                ctr++;\n                mutex.notifyAll();\n            }\n        }\n    }\n}\n```
['Java']