@@ -0,0 +1,1770 @@
+package main.algorithm.leetcode;%0A%0Aimport org.junit.Test;%0Aimport org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0Aimport java.util.concurrent.Semaphore;%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 PrintFooBarAlternately2 %7B%0A%0A    private static Logger logger = LoggerFactory.getLogger(PrintFooBarAlternately2.class);%0A%0A    static class FooBar %7B%0A%0A        private int n;%0A%0A        private Semaphore foo;%0A        private Semaphore bar;%0A%0A        public FooBar(int n) %7B%0A            this.n = n;%0A            foo = new Semaphore(1);%0A            bar = new Semaphore(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                foo.acquire();%0A                printFoo.run();%0A                bar.release();%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                bar.acquire();%0A                printBar.run();%0A                foo.release();%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 -- semaphore solution