/**
* Causes the current thread to wait until another thread invokes the
* {@link java.lang.Object#notify()} method or the
* {@link java.lang.Object#notifyAll()} method for this object.
* In other words, this method behaves exactly as if it simply
* performs the call {@code wait(0)}.
* <p>
* The current thread must own this object's monitor. The thread
* releases ownership of this monitor and waits until another thread
* notifies threads waiting on this object's monitor to wake up
* either through a call to the {@code notify} method or the
* {@code notifyAll} method. The thread then waits until it can
* re-obtain ownership of the monitor and resumes execution.
* <p>
* As in the one argument version, interrupts and spurious wakeups are
* possible, and this method should always be used in a loop:
* <pre>
* synchronized (obj) {
* while (<condition does not hold>)
* obj.wait();
* ... // Perform action appropriate to condition
* }
* </pre>
* This method should only be called by a thread that is the owner
* of this object's monitor. See the {@code notify} method for a
* description of the ways in which a thread can become the owner of
* a monitor.
*
* @throws IllegalMonitorStateException if the current thread is not
* the owner of the object's monitor.
* @throws InterruptedException if any thread interrupted the
* current thread before or while the current thread
* was waiting for a notification. The <i>interrupted
* status</i> of the current thread is cleared when
* this exception is thrown.
* @see java.lang.Object#notify()
* @see java.lang.Object#notifyAll()
*/
@FastNative
public final native void wait() throws InterruptedException;
翻译一下,使当前线程进入等待状态,直到另外一个线程 调了notify notifyAll方法。换句话说,等价于调了wait(0)
当前线程拥有对象锁,当前线程释放对象锁,一直等待。直到另一个线程通过调用notify/notifyAll来通知所有等待对象锁的线程进入激活态。等待线程 一直等待到重新获取对象锁后,执行后面方法。
调用方法参考。wait及后续的执行需要被包裹在一个循环里。
* synchronized (obj) {
* while (<condition does not hold>)
* obj.wait();
* ... // Perform action appropriate to condition
* }
* </pre>
https://blog.csdn.net/weixin_41101173/article/details/79889464
https://blog.csdn.net/u010002184/article/details/82893175
wait和notify是基于锁来做线程同步,基于同一个对象锁之间的多个线程之间同步。
②wait()释放CPU执行权,也释放同步锁,使得其他线程可以使用同步控制块或者方法。
首先要理解 notify() 和 wait(),这两个方法本来就不属于 Thread 类,而是属于最底层的 object 基础类的,也就是说不光是 Thread,每个对象都有 notify 和wait 的功能,为什么?因为他们是用来操纵锁的,而每个对象都有锁,锁是每个对象的基础,既然锁是基础的,那么操纵锁的方法当然也是最基础了。