1. 程式人生 > >synchronized內建鎖可重入性

synchronized內建鎖可重入性

如果某個執行緒檢視獲得一個已經由它自己持有的鎖,那麼這個請求就會成功。

public class Father {
protected synchronized void say() {
System.out.println(Thread.currentThread().getName() + " :father say!");
}
}

public class Child extends Father {
public synchronized void say() {
super.say();
System.out.println(Thread.currentThread().getName() + ": child say!");
}


public synchronized void sing() {
System.out.println(Thread.currentThread().getName() + ": child sing!");
for(;;){}
}
}

public class SynchronizedTest {
public static void main(String[] args) {
final Child child = new Child();
new Thread(new Runnable() {
@Override
public void run() {
child.say();
child.sing();
}
}).start();


new Thread(new Runnable() {
@Override
public void run() {
child.say();
child.sing();
}
}).start();
}
}

輸出

Thread-0 :father say!
Thread-0: child say!
Thread-0: child sing!

可以看到,Thread-0可以訪問當前執行緒其它(包括父類)鎖方法,但由於Child 類的sing方法出現死鎖,導致Thread-1處於等待狀態。

執行緒dump如下


再來看看,對Child和Father的鎖物件。

public class Father {
protected synchronized void say() {
System.out.println(Thread.currentThread().getName() + " :father say!");
for(;;){}
}
}


在Father類新增for(;;){}後,可以看到,Father  中say方法的鎖物件是Child的例項。