關于 synchronized 的使用??? jaja -------------------------------------------------------------------------------- synchronized 是對某一方法或對象加鎖, 只有擁有鎖才能訪問執行方法或其括號中的代碼, OK, 這個道理我明白, 但是好象實際卻不是這回事. public class SyncTest{ public static void main(String[] args){ final StringBuffer s1=new StringBuffer(); final StringBuffer s2=new StringBuffer(); new Thread() { public void run(){//只有擁有s1的鎖,才可以執行后面的代碼, synchronized(s1){ //現在當前線程有S1的鎖 s1.append("A"); synchronized(s2){ // 當前線程有S2的鎖嗎, 我不知道?? 好象有吧 s2.append("B"); System.out.print(s1); System.out.print(s2); } } } }.start();// 如果有S2的鎖, 打印出AB new Thread(){ public void run(){ synchronized(s2){//當前線程有S2的鎖嗎??? 我一點也不知道 s2.append("C"); synchronized(s1){ s1.append("D"); System.out.println(s2); System.out.println(s1); } } } }.start(); } }
哪位兄臺可以詳解一下? MM先行謝過
小烏 -------------------------------------------------------------------------------- the lock of the objects will be released after the synchronized code
public class SyncTest{ public static void main(String[] args){ final StringBuffer s1=new StringBuffer(); final StringBuffer s2=new StringBuffer(); new Thread() { public void run(){// synchronized(s1){ // 現在當前線程有S1的鎖 s1.append("A"); synchronized(s2){ // 當前線程擁有有S2的鎖 s2.append("B"); System.out.print(s1); System.out.print(s2); }// 釋放S2的鎖 } // 釋放S1的鎖 } }.start();// 如果有S2的鎖, 打印出AB new Thread(){ public void run(){ synchronized(s2){// 當前線程有S2的鎖 s2.append("C"); synchronized(s1){ // 現在當前線程有S1的鎖 s1.append("D"); System.out.println(s2); System.out.println(s1); } // 釋放S1的鎖 } // 釋放S2的鎖 } }.start(); } }
chairyuan -------------------------------------------------------------------------------- GG我來也: 這個程序之所以顯得正確,是因為每個thread都非常之快地運行結束。
public class SyncTest{ public static void main(String[] args){ final StringBuffer s1=new StringBuffer(); final StringBuffer s2=new StringBuffer(); new Thread() { public void run(){//只有擁有s1的鎖,才可以執行后面的代碼, synchronized(s1){ //現在當前線程有S1的鎖 s1.append("A"); synchronized(s2){ // 當前線程有S2的鎖 s2.append("B"); System.out.print(s1); System.out.print(s2); } } } }.start();// 如果足夠快的話,當前線程結束運行,釋放S1和S2的鎖。 new Thread(){//此時上一個線程可能已經結束,S1和S2的鎖都已經釋放。 public void run(){ synchronized(s2){//當前線程有S2的鎖 s2.append("C"); synchronized(s1){//當前線程有S2的鎖 s1.append("D"); System.out.println(s2); System.out.println(s1); } } } }.start(); } }
你可以試驗一下,在兩個線程中各加上幾個yield(),當第一個線程剛剛得到S1時,第二個線程已經得到了S2的鎖。然后第一個線程在等S2,第二個線程等S1,就會形成死鎖。 Java本身并沒有提供避免這種死鎖的方法,只有靠程序員自己去注意了。因此,良好的程序設計方法是,(盡量)保持同樣的順序去獲取鎖。
--------------------------------------------------------------------------------
|