Object类中wait带参数方法和notify

进入到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();

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