使用synchronized,wait,notifyAll 实现两个线程交替打印

package customer;

/**
 * @Author lizhilong
 * @create 2020/7/6 22:22
 * @desc
 */
public class ExchangePrint {
    public static void main(String[] args) {


        Object object = new Object();
        new Thread(()->{
            char a = 'A';
            synchronized (object){
                for(int i=0;i<26;i++){
                    System.out.println(a);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    a++;
                    object.notifyAll();
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            synchronized (object){
                for(int i=1;i<27;i++){
                    System.out.println(i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    object.notifyAll();
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

运行结果:

使用synchronized,wait,notifyAll 实现两个线程交替打印

上一篇:8.21Java入门--->第二十四节(多线程)


下一篇:notify()和notifyAll()有什么区别?什么是Daemon线程?