object.wait为什么要和synchronized一块使用
Object.wait 中JDK提供的doc文档
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.
In other words, this method behaves exactly as if it simply performs the call wait(0). 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 notify method or the notifyAll method.
The thread then waits until it can re-obtain ownership of the monitor and resumes execution. As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop: synchronized (obj) { while (<condition does not hold>) obj.wait(); ... // Perform action appropriate to condition } This method should only be called by a thread that is the owner of this object's monitor.
See the notify method for a description of the ways in which a thread can become the owner of a monitor.
一个对象的monitor只能被一个线程占用,wait()方法会释放这个对象的锁, 既然要释放 就先要取得这个锁, 取得对象锁的方式只有synchronized()。释放锁之后, 线程进入BLOCK状态
doc文档中说明调用wait的时机是因为运行条件condition不满足,
比如生产者没有往队列中放东西,队列已经空了。队列不为空的时候,再调用obj.notify()。此时condation==队列,obj是针对这个队列的线程间共享变量,也可以是队列本身(最好不是,会阻塞生产者的线程)?
@@@build beautiful things, share happiness@@@