JAVA单排日记-2020/1/20-Object类中的wait(参数)与notifyAll

  • wait(等待时间);
    等待时间结束后还没有notify()唤醒,会自动唤醒
public class Demo01 {
    public static void main(String[] args) {
        Object obj = new Object();

        new Thread(){
            @Override
            public void run() {
                System.out.println("等待");
                synchronized (obj){
                    try {
                        obj.wait(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("唤醒");
            }
        }.start();
    }
}

在这里插入图片描述

  • notifyAll()
    唤醒所有等待线程
public class Demo01 {
    public static void main(String[] args) {
        Object obj = new Object();

        new Thread() {
            @Override
            public void run() {
                System.out.println("顾客1等待");
                synchronized (obj) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("顾客1唤醒");
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                System.out.println("顾客2等待");
                synchronized (obj) {
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("顾客2唤醒");
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (obj) {
                    System.out.println("5s以后");
                    System.out.println("包子好了");
                    obj.notifyAll();
                }
            }
        }.start();
    }
}

在这里插入图片描述

发布了90 篇原创文章 · 获赞 1 · 访问量 2042

猜你喜欢

转载自blog.csdn.net/wangzilong1995/article/details/104053896