java synchronized同步方法調(diào)用另一個(gè)同步方法,鎖機(jī)制問(wèn)題
Posted on 2013-10-13 23:17 云云 閱讀(469) 評(píng)論(0) 編輯 收藏public synchronized void methodA(int a, int b);
public synchronized void methodB(int a){
methodA(a, 0);
}
這樣的代碼是成立的,一個(gè)線程對(duì)同一個(gè)對(duì)象的鎖可以反復(fù)獲取。這種同步鎖稱為可重入的鎖。
加在非static方法上的synchronized方法是和synchronized(this)塊等價(jià)的,均為對(duì)象鎖,即對(duì)this加鎖。
獲得當(dāng)前對(duì)象鎖的線程,可以繼續(xù)獲得當(dāng)前對(duì)象鎖,JVM負(fù)責(zé)跟蹤對(duì)象被加鎖的次數(shù)。線程運(yùn)行B方法,此時(shí)如果this鎖可以用,線程獲得該鎖,線程給對(duì)象加鎖,計(jì)數(shù)器變成1,然后B方法調(diào)用A方法,由于是對(duì)同一個(gè)對(duì)象同一個(gè)線程,線程可以繼續(xù)獲得鎖,計(jì)數(shù)器變?yōu)?,表示this被加鎖2次。A方法完畢后,線程釋放鎖,計(jì)數(shù)器變?yōu)?,此時(shí)對(duì)象鎖對(duì)其他線程依然是不可獲得的。B方法完畢后,線程繼續(xù)釋放鎖,此時(shí)計(jì)數(shù)器變?yōu)?,表示鎖被完全釋放,其他線程可以獲得對(duì)象鎖。
public synchronized void methodA(int a, int b){
}
public synchronized void methodB(int a, int b){
}
以上兩方法在同一實(shí)例對(duì)象上是互斥的,synchronized 加在方法上 即對(duì)this加鎖,因此在同一實(shí)例對(duì)象上 兩方法是互斥的。
public synchronized void methodB(int a){
methodA(a, 0);
}
這樣的代碼是成立的,一個(gè)線程對(duì)同一個(gè)對(duì)象的鎖可以反復(fù)獲取。這種同步鎖稱為可重入的鎖。
加在非static方法上的synchronized方法是和synchronized(this)塊等價(jià)的,均為對(duì)象鎖,即對(duì)this加鎖。
獲得當(dāng)前對(duì)象鎖的線程,可以繼續(xù)獲得當(dāng)前對(duì)象鎖,JVM負(fù)責(zé)跟蹤對(duì)象被加鎖的次數(shù)。線程運(yùn)行B方法,此時(shí)如果this鎖可以用,線程獲得該鎖,線程給對(duì)象加鎖,計(jì)數(shù)器變成1,然后B方法調(diào)用A方法,由于是對(duì)同一個(gè)對(duì)象同一個(gè)線程,線程可以繼續(xù)獲得鎖,計(jì)數(shù)器變?yōu)?,表示this被加鎖2次。A方法完畢后,線程釋放鎖,計(jì)數(shù)器變?yōu)?,此時(shí)對(duì)象鎖對(duì)其他線程依然是不可獲得的。B方法完畢后,線程繼續(xù)釋放鎖,此時(shí)計(jì)數(shù)器變?yōu)?,表示鎖被完全釋放,其他線程可以獲得對(duì)象鎖。
public synchronized void methodA(int a, int b){
}
public synchronized void methodB(int a, int b){
}
以上兩方法在同一實(shí)例對(duì)象上是互斥的,synchronized 加在方法上 即對(duì)this加鎖,因此在同一實(shí)例對(duì)象上 兩方法是互斥的。