三个线程交替打印ABC代码--面试题

public class PrinterABC2 {

    static Thread printA;
    static Thread printB;
    static Thread printC;

    public static void main(String[] args) {

        printA = new Thread(() -> {
            while (true) {
                LockSupport.park();
                System.out.println("A");
                if (printB != null) {
                    LockSupport.unpark(printB);
                }
            }
        });
        printB = new Thread(() -> {
            while (true) {
                LockSupport.park();
                System.out.println("B");
                if (printB != null) {
                    LockSupport.unpark(printC);
                }
            }
        });
        printC = new Thread(() -> {
            while (true) {
                LockSupport.park();
                System.out.println("C");
                if (printA != null) {
                    LockSupport.unpark(printA);
                }
            }
        });

        printA.start();
        printB.start();
        printC.start();
        LockSupport.unpark(printA);
    }
}

你可能感兴趣的:(笔记)