[JAVA] Two Methods 【CAS】ans【synchronized】
1. CAS\n\nimport java.util.concurrent.atomic.AtomicInteger;\n\nclass Foo {\n\n\tAtomicInteger count = new AtomicInteger();\n\n\tpublic Foo() {\n\t\tcount.set(0)
**1. CAS**\n```\nimport java.util.concurrent.atomic.AtomicInteger;\n\nclass Foo {\n\n\tAtomicInteger count = new AtomicInteger();\n\n\tpublic Foo() {\n\t\tcount.set(0);\n\t}\n\n\tpublic void first(Runnable printFirst) throws InterruptedException {\n\n\t\twhile (!count.compareAndSet(0, 4)) {\n\t\t\t// printFirst.run() outputs "first". Do not change or remove this line.\n\t\t}\n\t\tprintFirst.run();\n\t\tcount.set(1);\n\t}\n\n\tpublic void second(Runnable printSecond) throws InterruptedException {\n\t\twhile (!count.compareAndSet(1, 4)) {\n\t\t\t// printSecond.run() outputs "second". Do not change or remove this line.\n\t\t}\n\t\tprintSecond.run();\n\t\tcount.set(2);\n\n\t}\n\n\tpublic void third(Runnable printThird) throws InterruptedException {\n\t\twhile (!count.compareAndSet(2, 4)) {\n\t\t\t// printThird.run() outputs "third". Do not change or remove this line.\n\t\t}\n\t\tprintThird.run();\n\t\tcount.set(3);\n\t}\n}\n```\n\n\n**2. Synchronized**\n```\nimport java.util.concurrent.locks.*;\n\nclass Foo {\n\n    int count = 0;\n    \n    public Foo() {\n    }\n\n    public synchronized void first(Runnable printFirst) throws InterruptedException {\n        \n        \n        printFirst.run();\n        count++;\n        this.notifyAll();\n\n    }\n\n    public synchronized void second(Runnable printSecond) throws InterruptedException {\n        \n        while(count != 1){\n           this.wait();\n        }\n        printSecond.run();\n        count++;\n        this.notifyAll();\n    }\n\n    public synchronized void third(Runnable printThird) throws InterruptedException {\n\n        while(count != 2){\n          this.wait();\n        }\n        printThird.run();\n        count++;\n    }\n}\n```
[]