@@ -0,0 +1,2302 @@
+package main.algorithm.leetcode;%0A%0Aimport org.junit.Test;%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0Aimport java.util.concurrent.atomic.AtomicInteger;%0A%0A/**%0A * Title : main.algorithm.leetcode %3Cbr%3E%0A * Description :%0A *%0A *%0A * @author chile%0A * @version 1.0%0A * @date 2020/11/19 14:56%0A */%0Apublic class PrintFooBarAlternately %7B%0A%0A    private static Logger logger = LoggerFactory.getLogger(PrintFooBarAlternately.class);%0A%0A    static class FooBar %7B%0A%0A        private int n;%0A%0A        private static final Object LOCK = new Object();%0A%0A        private AtomicInteger flag;%0A%0A        public FooBar(int n) %7B%0A            this.n = n;%0A            this.flag = new AtomicInteger(0);%0A        %7D%0A%0A        public void foo(Runnable printFoo) throws InterruptedException %7B%0A%0A            for (int i = 0; i %3C n; i++) %7B%0A                synchronized (LOCK) %7B%0A                    if (flag.get() != 0) %7B%0A                        LOCK.wait();%0A                    %7D%0A                    // printFoo.run() outputs %22foo%22. Do not change or remove this line.%0A                    printFoo.run();%0A                    flag.set(1);%0A                    LOCK.notifyAll();%0A                %7D%0A            %7D%0A        %7D%0A%0A        public void bar(Runnable printBar) throws InterruptedException %7B%0A%0A            for (int i = 0; i %3C n; i++) %7B%0A                synchronized (LOCK) %7B%0A                    if (flag.get() != 1) %7B%0A                        LOCK.wait();%0A                    %7D%0A                    // printBar.run() outputs %22bar%22. Do not change or remove this line.%0A                    printBar.run();%0A                    flag.set(0);%0A                    LOCK.notifyAll();%0A                %7D%0A            %7D%0A        %7D%0A    %7D%0A%0A    @Test%0A    public void test() throws InterruptedException%7B%0A        FooBar fb = new FooBar(3);%0A%0A        Thread t1 = new Thread(() -%3E %7B%0A            try %7B%0A                fb.foo(() -%3E System.out.println(%22foo%22));%0A            %7D catch (InterruptedException e) %7B%0A                e.printStackTrace();%0A            %7D%0A        %7D);%0A        Thread t2 = new Thread(() -%3E %7B%0A            try %7B%0A                fb.bar(() -%3E System.out.println(%22bar%22));%0A            %7D catch (InterruptedException e) %7B%0A                e.printStackTrace();%0A            %7D%0A        %7D);%0A%0A        t1.start();%0A        t2.start();%0A%0A        Thread.sleep(1000);%0A    %7D%0A%7D%0A

print foobar alternately -- synchronized solution