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是針對這個隊列的線程間共享變量,也可以是隊列本身(最好不是,會阻塞生產者的線程)?

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM