java多線程中Object.wait()和Condition.await()是否會釋放當前線程鎖占有的鎖


我剛開始深入研究多線程,一直認為Object.wait()/Condition.await()讓當前線程阻塞的同時,也會釋放當前線程對該condition對象的鎖。在之前的一些測試代碼中也顯示wait后,線程上的鎖被釋放了。但是我們經理卻堅持當前線程會占用鎖。

查看Object.wait()API 描述如下:

    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. 

其中“the thread releases ownership of this monitor” 說道當前線程會釋放這個對象監控器的所有權。

問題一:這里的monitor怎么理解?監視器(monitor)和鎖是什么關系? 這個monitor就是一個術語,或者是一個特殊的類(只包含私有域),但是在java中並沒有嚴格遵守這個概念。個人認為可以簡單的理解為鎖。

同樣的,Condition.await()方法中也有類似描述。

    The lock associated with this Condition is atomically released and the current thread becomes disabled for thread scheduling purposes... 

也說道,調用await()有,這個條件對象關聯的鎖被“原子級地”釋放。。。

問題二:這個原子級的釋放是什么意思? “原子級”其實就是為了保證一個操作的完整性,原子級的釋放保證了一個原子操作不會因為線程的突然掛起或者說阻塞而破壞這次操作。

這都能說明調用wait()或者await()后,當前線程會釋放該條件對象關聯的鎖吧


免責聲明!

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



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