Simple java solution with explanation
Simple Java solution with two Semaphores.\n\nimport java.util.concurrent.*;\nclass FooBar {\n    private int n;\n    private Semaphore one, two; //Declaring two
Simple Java solution with two Semaphores.\n```\nimport java.util.concurrent.*;\nclass FooBar {\n    private int n;\n    private Semaphore one, two; //Declaring two Semaphores.\n\n    public FooBar(int n) {\n        this.n = n;\n        one = new Semaphore(1); //First semaphore initialized with one permit available\n        two = new Semaphore(0); //Second Semaphore initialized with no permits\n    }\n\n    public void foo(Runnable printFoo) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            one.acquire(); // Acquire first semaphore wich have one permit, no permits remaining\n        \t// printFoo.run() outputs "foo". Do not change or remove this line.\n        \tprintFoo.run();\n            two.release(); //Add one permit to second semaphore\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            two.acquire(); //Waits till one permit will be added in foo method, then acquire it\n            // printBar.run() outputs "bar". Do not change or remove this line.\n        \tprintBar.run();\n            one.release(); // add one permit to first Semaphore\n        }\n    }\n}\n```
[]