[Java] Just volatile
\nclass FooBar {\n    \n\tprivate final int n;\n    \n    private volatile boolean flag;\n\n    public FooBar(int n) {\n        this.flag = false;\n        this
```\nclass FooBar {\n    \n\tprivate final int n;\n    \n    private volatile boolean flag;\n\n    public FooBar(int n) {\n        this.flag = false;\n        this.n = n;\n    }\n\n    public void foo(Runnable printFoo) throws InterruptedException {\n        for (int i = 0; i < n; i++) {\n            while(flag){\n                Thread.yield();\n            }\n        \tprintFoo.run();\n            flag = true;\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        for (int i = 0; i < n; i++) {\n            while(!flag){\n                Thread.yield();\n            }\n        \tprintBar.run();\n            flag = false;\n        }\n    }\n}\n```
[]