----------- android培訓、java培訓、java學習型技術博客、期待與您交流! ------------
public class Test {
public static void main(String [] args){
syn1 ss1=new syn1();
syn2 ss2=new syn2();
new Thread(ss1).start();
new Thread(ss1).start();
new Thread(ss2).start();
}
}
class syn1 implements Runnable{
public String str1="";//new String("");//改成new String("");
public void run() {
synchronized(str1){
while(true){
try{Thread.sleep(1);}catch(Exception e){}
System.out.println("syn1:"+Thread.currentThread().getName());
}
}
}
}
class syn2 implements Runnable{
public String str2="";//new String("");////改成new String("");
public void run() {
synchronized(str2){
while(true){
try{Thread.sleep(1);}catch(Exception e){}
System.out.println("syn2:"+Thread.currentThread().getName());
}
}
}
}
str1與str2其實是同一個對象,在第一個線程運行時,對該對象上了鎖,因此每二個線程阻塞等待。這樣寫str1=new String("")和str2=new String("")就可以了
----------- android培訓、java培訓、java學習型技術博客、期待與您交流! ------------