Java synchronized之“可重入鎖”
阿新 • • 發佈:2019-01-09
概念
可重入鎖:自己可以再次獲取自己的內部的鎖。比如有執行緒A獲得了某物件的鎖,此時這個時候鎖還沒有釋放,當其再次想獲取這個物件的鎖的時候還是可以獲取的,如果不可鎖重入的話,就會造成死鎖。
可重入鎖也支援在父子類繼承的環境中。
例項
package com.test.sync;
public class Main {
public int i = 10;
synchronized public void operateMainMethod(){
try {
i --;
System.out.println("main print i = " + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.test.sync;
public class Sub extends Main{
synchronized public void operateISubMethod(){
try {
while(i>0){
i --;
System.out.println("sub print i=" +i);
Thread.sleep(100);
this.operateMainMethod();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.test.sync;
public class MyThread extends Thread{
@Override
public void run() {
Sub sub = new Sub();
sub.operateISubMethod();
}
}
package com.test.sync;
public class Test {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
執行結果如下:
sub print i=9
main print i = 8
sub print i=7
main print i = 6
sub print i=5
main print i = 4
sub print i=3
main print i = 2
sub print i=1
main print i = 0
這說明,子類繼承父類時,子類完全可以通過可重入鎖呼叫父類的同步方法。