使用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();
    }
}

运行结果:

posted @ 2020-08-07 19:25  脆皮香蕉  阅读(388)  评论(0编辑  收藏  举报