Java Solution using only shared global variable.(Using Yield)
\nclass FooBar {\n    private int n;\n    Boolean flag;\n\n    public FooBar(int n) {\n        this.n = n;\n        flag = true;\n    }\n\n    public void foo(R
```\nclass FooBar {\n    private int n;\n    Boolean flag;\n\n    public FooBar(int n) {\n        this.n = n;\n        flag = true;\n    }\n\n    public void foo(Runnable printFoo) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n               while(flag!=true)\n                   Thread.yield();\n                printFoo.run();\n                flag = false; \n        \t// printFoo.run() outputs "foo". Do not change or remove this line.\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            while(flag!=false)\n                Thread.yield();\n            // printBar.run() outputs "bar". Do not change or remove this line.\n        \tprintBar.run(); \n            flag = true;\n            }\n    }\n}\n```
[]