首页 > 其他 > 详细

Object类中wait带参数方法和notify

时间:2020-09-28 00:59:26      阅读:49      评论:0      收藏:0      [点我收藏+]

进入到TimeWaiting(计时等待)有两种方法

1.使用sleep方法,在毫秒值结束后,线程睡醒进入到Runnable/blocked状态

2.使用wait方法,wait方法如果在毫秒值结束后,还没有被notify唤醒,就会自动醒来,线程睡醒进入到Runnable/blocked状态

唤醒方法:

   void notify()

    唤醒在此对象监视器上等待的单个线程。

void notifyAll()唤醒在此对象监视器上的等待的所有线程

 

 

public class Demo02WaitAndNotify {
public static void main(String[] args) {
Object obj =new Object();
new Thread(){
@Override
public void run() {
while (true){
synchronized (obj){
System.out.println("告知老板要的包子的种类和数量");
try {
obj.wait(5000);//wait
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子已经做好了开吃");
}
}
}
}.start();
}
}

 

notifyAll()

public class Demo02WaitAndNotify {
    public static void main(String[] args) {
        Object obj =new Object();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    synchronized (obj){
                        System.out.println("1告知老板要的包子的种类和数量");
                        try {
                            obj.wait();//wait
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("1包子已经做好了开吃");
                        System.out.println("======");
                    }
                }
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    synchronized (obj){
                        System.out.println("2告知老板要的包子的种类和数量");
                        try {
                            obj.wait();//wait
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("2包子已经做好了开吃");
                        System.out.println("========");
                    }
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (obj){
                        System.out.println("老板5秒之后做好包子告诉顾客可以吃包子");
                        obj.notifyAll();
                    }
                }

            }
        }.start();

    }
}

 

Object类中wait带参数方法和notify

原文:https://www.cnblogs.com/cy2268540857/p/13742581.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!