Using semaphore java
class FooBar {\n    private int n;\n\n    Semaphore s1 = new Semaphore(1);\n    Semaphore s2 = new Semaphore(0);\n    \n    public FooBar(int n) {\n        this
class FooBar {\n    private int n;\n\n    Semaphore s1 = new Semaphore(1);\n    Semaphore s2 = new Semaphore(0);\n    \n    public FooBar(int n) {\n        this.n = n;\n    }\n\n    public void foo(Runnable printFoo) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            s1.acquire();\n        \t// printFoo.run() outputs "foo". Do not change or remove this line.\n        \tprintFoo.run();\n           s2.release();\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n           s2.acquire();\n            // printBar.run() outputs "bar". Do not change or remove this line.\n        \tprintBar.run();\n            s1.release();\n        }\n    }\n}
[]