[Java] Semaphore in Details Explanation With Brute Force Example
Brute Force Approach\n\n\nclass FooBar {\n    private int n;\n    int c = 0;\n    public FooBar(int n) {\n        this.n = n;\n    }\n\n    public void foo(Runn
# Brute Force Approach\n\n```\nclass FooBar {\n    private int n;\n    int c = 0;\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            while(c>0){\n                continue;\n            }\n        \t// printFoo.run() outputs "foo". Do not change or remove this line.\n        \tprintFoo.run();\n            c++;\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            while(c<1){\n                continue;\n            }\n            // printBar.run() outputs "bar". Do not change or remove this line.\n        \tprintBar.run();\n            c--;\n        }\n    }\n}\n```\n\nThe while loop is just like acquiring lock. But this is exhaustive and will result into **TLE**. So, we have no choice but to use `Semaphores`.\n\n\n# Solution Using Semaphore\n\n```\nclass FooBar {\n    private int n;\n    Semaphore foo_lock, bar_lock;\n    public FooBar(int n) {\n        this.n = n;\n        foo_lock = new Semaphore(1); // foo can pass\n        bar_lock = new Semaphore(0); // bar cannot\n    }\n\n    public void foo(Runnable printFoo) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            foo_lock.acquire(); // foo_lock is 1, so acquire lock\n            // acquired lock. foo_lock = 0 now..\n        \t// printFoo.run() outputs "foo". Do not change or remove this line.\n        \tprintFoo.run();\n            bar_lock.release(); // released lock. bar_lock = 1 now..\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            bar_lock.acquire(); // bar_lock is 1, so acquire lock\n            // bar_lock = 0 now..\n            // printBar.run() outputs "bar". Do not change or remove this line.\n        \tprintBar.run();\n            foo_lock.release(); // released lock. foo_lock = 1 now..\n        }\n    }\n}\n```\n\nYou probably know the basics of **Semaphores**. To acquire locks semaphore values need to be > 0. When the value is <= 0 we cannot acquire lock of that `Semaphore`.
['Java']