多线程循环打印abc


import java.util.concurrent.CountDownLatch;

public class PrintXYZ {
    private CountDownLatch xCount = new CountDownLatch(1);
    private CountDownLatch yCount = new CountDownLatch(1);
    private CountDownLatch zCount = new CountDownLatch(1);

    public void print() {

        Thread threadA = new Thread() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        xCount.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("X");
                    yCount.countDown(); //忘了具体方法了 应该不对
                    xCount = new CountDownLatch(1);
                }
            }
        };

        Thread threadB = new Thread() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        yCount.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Y");
                    zCount.countDown(); //忘了具体方法了 应该不对
                    yCount = new CountDownLatch(1);
                }
            }
        };

        Thread threadC = new Thread() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        zCount.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Z");
                    if (i < 9) {
                        xCount.countDown(); //忘了具体方法了 应该不对
                        zCount = new CountDownLatch(1);
                    }

                }
            }
        };
        threadC.start();
        threadB.start();
        threadA.start();
    }

    public static void main(String[] args) {
        PrintXYZ printXYZ = new PrintXYZ();
        printXYZ.print();
        printXYZ.xCount.countDown();
    }
}
上一篇:闭锁


下一篇:countDownLatch