object.wait为什么要和synchronized一块使用
Posted yszzu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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是针对这个队列的线程间共享变量,也可以是队列本身(最好不是,会阻塞生产者的线程)?
以上是关于object.wait为什么要和synchronized一块使用的主要内容,如果未能解决你的问题,请参考以下文章
Object.wait()与Object.notify()的用法