[摘要]关于 synchronized 的使用???jaja-------------------------------------------------------------------------...
关于 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本身并没有提供避免这种死锁的方法,只有靠程序员自己去注意了。因此,良好的程序设计方法是,(尽量)保持同样的顺序去获取锁。 
--------------------------------------------------------------------------------   
关键词:转自别的论坛的一篇对于synchronized的讨论