四个线程不断的打印ABCD 使用ReentrentLock实现

151 阅读1分钟
@Slf4j(topic = "c.singleton")
public class Singleton {
    static volatile int index = 0;
    static ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Condition c1 = lock.newCondition();
        Condition c2 = lock.newCondition();
        Condition c3 = lock.newCondition();
        Condition c4 = lock.newCondition();

        new Thread(() -> {
            printABCD("A",c1,c2,0);
        }, "t1").start();
        new Thread(() -> {
            printABCD("B",c2,c3,1);
        }, "t2").start();
        new Thread(() -> {
            printABCD("C",c3,c4,2);
        }, "t3").start();
        new Thread(() -> {
            printABCD("D",c4,c1,3);
        }, "t4").start();

        Thread.sleep(20);
        index = 0;
    }


    public static  void printABCD(String s,Condition current,Condition next,int num){
        while (true){
            lock.lock();
            try {
                while(index%4!=num){
                    current.await();
                }
                index++;
                log.debug(s);
                next.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }

    }
}