公众号:架构师与哈苏
关注公众号进入it交流群! 公众号:架构师与哈苏 不定时都会推送一些实用的干货。。。
public static Object obj1 = new Object();

public static void printAB(){

    Thread t1 = new Thread(() -> {
        while (true){
            synchronized (obj1) {
                System.out.println("T1:A");
                obj1.notify();
                try {
                    Thread.sleep(1000);
                    obj1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    Thread t2 = new Thread(() -> {
        while (true){
            synchronized (obj1) {
                System.out.println("T2:B");
                obj1.notify();
                try {
                    Thread.sleep(1000);
                    obj1.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    t1.start();
    t2.start();

}
posted on 2021-08-23 17:33  公众号/架构师与哈苏  阅读(81)  评论(0编辑  收藏  举报