前提:wait和notify、notifyAll都只能在
同步代码块或者
同步方法中调用,且要通过
锁对象进行调用,否则会抛出
IllegalMonitorStateException
1.wait
-
wait(),当前线程进入 无限等待状态,必须被唤醒才能继续执行,调用后会释放锁对象
-
wait(long timeout),wait(long timeout,int nanos),当前线程进入等待状态,可以被提前唤醒,但在指定时间后会自动唤醒
2.notify
-
notify(), 随机唤醒一个在锁对象上调用wait的线程
-
notifyAll(),唤醒 全部在锁对象上调用wait的线程
例子:
![](https://img-blog.csdnimg.cn/20200623203019817.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMxMDc1MDQx,size_16,color_FFFFFF,t_70)
![](https://img-blog.csdnimg.cn/20200623203019814.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzMxMDc1MDQx,size_16,color_FFFFFF,t_70)