[Java] Solution using Semaphore
Using Semaphore, we want two threads to run n times. Each time, the thread \'foo\' will acquire the semaphore and the print foo, then the other thread \'bar\' w
Using Semaphore, we want two threads to run n times. Each time, the thread \'foo\' will acquire the semaphore and the print foo, then the other thread \'bar\' would acquire the semaphore and print \'bar\'. Once we do this n times, both threads will end at the same time. \n\n\n\n\'\'\'\nclass FooBar \n{\n\n\tprivate int n;\n\tSemaphore s_bar = new Semaphore(0);\n\tSemaphore s_foo = new Semaphore(1);\n\tpublic FooBar(int n) {\n\t\tthis.n = n;\n\t}\n\t\n    public void foo(Runnable printFoo) throws InterruptedException {\n        for (int i = 0; i < n; i++) {\n            s_foo.acquire();\n        \t// printFoo.run() outputs "foo". Do not change or remove this line.\n        \tprintFoo.run();\n            s_bar.release();\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            s_bar.acquire();\n            // printBar.run() outputs "bar". Do not change or remove this line.\n        \tprintBar.run();\n            s_foo.release();\n        }\n    }\n}\n
[]