public synchronized void methodA(int a, int b);
public synchronized void methodB(int a){
methodA(a, 0);
}
這樣的代碼是成立的,一個線程對同一個對象的鎖可以反復獲取。這種同步鎖稱為可重入的鎖。
加在非static方法上的synchronized方法是和synchronized(this)塊等價的,均為對象鎖,即對this加鎖。
獲得當前對象鎖的線程,可以繼續獲得當前對象鎖,JVM負責跟蹤對象被加鎖的次數。線程運行B方法,此時如果this鎖可以用,線程獲得該鎖,線程給對象加鎖,計數器變成1,然后B方法調用A方法,由于是對同一個對象同一個線程,線程可以繼續獲得鎖,計數器變為2,表示this被加鎖2次。A方法完畢后,線程釋放鎖,計數器變為1,此時對象鎖對其他線程依然是不可獲得的。B方法完畢后,線程繼續釋放鎖,此時計數器變為0,表示鎖被完全釋放,其他線程可以獲得對象鎖。
public synchronized void methodA(int a, int b){
}
public synchronized void methodB(int a, int b){
}
以上兩方法在同一實例對象上是互斥的,synchronized 加在方法上 即對this加鎖,因此在同一實例對象上 兩方法是互斥的。
public synchronized void methodB(int a){
methodA(a, 0);
}
這樣的代碼是成立的,一個線程對同一個對象的鎖可以反復獲取。這種同步鎖稱為可重入的鎖。
加在非static方法上的synchronized方法是和synchronized(this)塊等價的,均為對象鎖,即對this加鎖。
獲得當前對象鎖的線程,可以繼續獲得當前對象鎖,JVM負責跟蹤對象被加鎖的次數。線程運行B方法,此時如果this鎖可以用,線程獲得該鎖,線程給對象加鎖,計數器變成1,然后B方法調用A方法,由于是對同一個對象同一個線程,線程可以繼續獲得鎖,計數器變為2,表示this被加鎖2次。A方法完畢后,線程釋放鎖,計數器變為1,此時對象鎖對其他線程依然是不可獲得的。B方法完畢后,線程繼續釋放鎖,此時計數器變為0,表示鎖被完全釋放,其他線程可以獲得對象鎖。
public synchronized void methodA(int a, int b){
}
public synchronized void methodB(int a, int b){
}
以上兩方法在同一實例對象上是互斥的,synchronized 加在方法上 即對this加鎖,因此在同一實例對象上 兩方法是互斥的。