[JAVA] CAS + volatile
Intuition\n Describe your first thoughts on how to solve this problem. \nUsing CAS + volatile\n# Approach\n Describe your approach to solving the problem. \n\n#
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing CAS + volatile\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass FooBar {\n    private int n;\n    private volatile boolean state;\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(state) {\n                continue;\n            }\n        \t// printFoo.run() outputs "foo". Do not change or remove this line.\n        \tprintFoo.run();\n            state = true;\n        }\n    }\n\n    public void bar(Runnable printBar) throws InterruptedException {\n        \n        for (int i = 0; i < n; i++) {\n            while(!state) {\n                continue;\n            }\n            // printBar.run() outputs "bar". Do not change or remove this line.\n        \tprintBar.run();\n            state = false;\n        }\n    }\n}\n\n```
['Java']