“可重入鎖”的概念是:自己可以再次獲得自己的內部鎖。比如有一條線程獲得了某個對象的鎖,此時這個對象還沒有釋放,當其再次想獲得這個對象的鎖的時候還是可以獲得的,如果不可鎖重入的話,就會造成死鎖。
class sysTest{ synchronized void test1(String str){ System.out.println(str+"1"); test2(str); System.out.println("end" + str); } synchronized void test2(String str){ System.out.println(str+"2"); } } class myThread extends Thread{ String str = null; public myThread(String str) { this.str = str; } @Override public void run() { // TODO Auto-generated method stub super.run(); new sysTest().test1(str); } } public class synchronizedTest { public static void main(String[] args) { // TODO Auto-generated method stub myThread th1 = new myThread("1str"); myThread th2 = new myThread("2str"); th1.start(); th2.start(); } }
在加粗的sychronized在的時候結果會有下面,結果不唯一的:
1str1
2str1
1str2
2str2
end2str
end1str
在加粗的sychronized去掉的時候結果會有下面,結果唯一的:
1str1
1str2
end1str
2str1
2str2
end2str
在這里必須要認識到,加一個sychronized方法里調用sychronized方法會造成不同步,需要注意。原因是兩個鎖的問題,
這個時候使用可重入概念解決的話,就要使用對象鎖,因為在sychronized()代碼塊中再次獲得該鎖就會可以得到:
class sysTest{ static Object object = new Object(); void test1(String str){ synchronized(object){ System.out.println(str+"1"); test2(str); System.out.println("end" + str); } } void test2(String str){ synchronized(object){ System.out.println(str+"2"); } } } class myThread extends Thread{ String str = null; public myThread(String str) { this.str = str; } @Override public void run() { // TODO Auto-generated method stub super.run(); new sysTest().test1(str); } } public class synchronizedTest { public static void main(String[] args) { // TODO Auto-generated method stub myThread th1 = new myThread("1str"); myThread th2 = new myThread("2str"); th1.start(); th2.start(); } } 結果: 1str1 1str2 end1str 2str1 2str2 end2str