Bootstrap

两个线程交替打印A1B2C3D4E5输出,6种实现方式

第一种,传统方式wait和notify

public static void main(String[] args) {
        Object o = new Object();
        char[]  chars1 = "12345".toCharArray();
        char[]  chars2 = "ABCDE".toCharArray();
        new Thread(()->{
            synchronized (o) {
                for (int i = 0; i < chars1.length; i++) {
                    System.out.print(chars1[i]);
                    o.notify();
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }

        },"t1").start();
        new Thread(()->{
            synchronized (o) {
                for (int i = 0; i < chars2.length; i++) {
                    System.out.print(chars2[i]);
                    o.notify();
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }

        },"t2").start();
    }

如上代码:思考两个问题wait和notify的顺序可以颠倒吗,为什么for循环后还要notify?

wait和notify的顺序不能颠倒,因为如果wait在前当前线程就在等待队列中,永远不会被唤醒了

for循环后还要加notify,是因为两个线程无论哪个最后执行&

;