java堆和棧的區(qū)別 java synchronized鎖對象,當對象引用是null的時候,鎖的是什么?
java synchronized鎖對象,當對象引用是null的時候,鎖的是什么?謝邀!Java語言規(guī)范中明確指出如果鎖住的對象是null,則會NullPointerException,規(guī)范內(nèi)容如下:
java synchronized鎖對象,當對象引用是null的時候,鎖的是什么?
謝邀!
Java語言規(guī)范中明確指出如果鎖住的對象是null,則會NullPointerException,規(guī)范內(nèi)容如下:
The type of Expression must be a reference type, or a compile-time error occurs. A synchronized statement is executed by first evaluating the Expression. Then: If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason. Otherwise, if the value of the Expression is null, a NullPointerException is thrown.
Java中非static的synchronized方法和synchronized(this)用的是一個鎖嗎?
Java中非static的synchronized方法和synchronized(this)用的是一把鎖,這也說明非靜態(tài)方法中的synchronized(this)和synchronized關(guān)鍵字
是Java支持中同一把鎖。
在Java中,synchronized是用來表示同步的,既可以用synchronized來修飾一個方法,也可以修飾方法里的語句塊。
在static方法和非static方法前面加synchronized的區(qū)別在于
static的方法屬于類方法,它屬于Class類范疇,所以static獲取到的鎖,是屬于類的鎖。
非static方法獲取到的鎖,是屬于當前對象的鎖。
再回到問題它們是一把鎖,synchronized是針對一個臨界區(qū)的,臨界區(qū)指訪問這個地方最多只能在一個線程里面,
它在對象上加鎖后進入臨界區(qū)以此來達到臨界區(qū)串行訪問的目的。
希望可以幫到你?。?!