Java semaphore solution - easy to understand
\nclass FooBar {\n    private int n;\n    private Semaphore sem1, sem2;\n\n    public FooBar(int n) {\n        this.n = n;\n        this.sem1 = new Semaphore(1)
```\nclass FooBar {\n    private int n;\n    private Semaphore sem1, sem2;\n\n    public FooBar(int n) {\n        this.n = n;\n        this.sem1 = new Semaphore(1);\n        this.sem2 = new Semaphore(0);\n    }\n\n    public void foo(Runnable printFoo) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            sem1.acquire();\n        \t// printFoo.run() outputs "foo". Do not change or remove this line.\n        \tprintFoo.run();\n            sem2.release();\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            sem2.acquire();\n            // printBar.run() outputs "bar". Do not change or remove this line.\n        \tprintBar.run();\n            sem1.release();\n        }\n    }\n}\n```
[]