wait() notify() 实际应用

1.需求

有三个线程:第一个线程输出:“+++++++++++++++++++++++”
第二个线程输出:“————————————-”
第三个线程输出:“**********************
现在要让这三个线程每一次输出都按照先*在-最后+的形式输出:

代码:

public class Demo {
    static  Object object=new Object();
    static int i=1;
    public static void main(String[] args) {
        new Thread(()->{
            synchronized (object) {
                while (i!=3){
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("+++++++++++++++");
            }
        }).start();
        new Thread(()->{
            synchronized (object) {
                while (i != 2) {
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("---------------------");
                i=3;
                object.notifyAll();
            }
        }).start();
        new Thread(()->{
            synchronized (object) {
                while (i!=1){
                    try {
                        object.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("*******************");
                i=2;
                object.notifyAll();
            }
        }).start();
    }
 }

猜你喜欢

转载自blog.csdn.net/woshijinfeixi/article/details/81772134