四个线程按序打印ABCD 使用synchronized wait notifyAll实现

117 阅读1分钟
static volatile int index = 0;
static Object object = new Object();

public static void main(String[] args) throws ExecutionException, InterruptedException {
    new Thread(() -> {
        printABCD("A",0);
    }).start();
    new Thread(() -> {
        printABCD("B",1);
    }).start();
    new Thread(() -> {
        printABCD("C",2);
    }).start();
    new Thread(() -> {
        printABCD("D",3);
    }).start();
}


public static void printABCD(String s, int num) {
    while (true) {
        synchronized (object) {
            while (index %4!= num) {
                try {
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            log.debug(s);
            index++;
            object.notifyAll();
        }
    }
}