public class Thread1 extends Thread {
public static String data = "" ;
public Thread1(String tname){
super(tname);
}
public void run(){
synchronized (Thread1.data){
for (int i = 0; i < 5; i++) {
if(this.getName().equals("T1")){
Thread1.data = "Thread1";
try {
Thread.sleep(1000);
}catch (InterruptedException e){}
System.out.println(getName()+":"+Thread1.data);
}else if (this.getName().equals("T2")){
Thread1.data = "Thread2";
try {
Thread.sleep(1000);
}catch (InterruptedException e){}
System.out.println(getName()+":"+Thread1.data);
}
}
}
}
}
public class Main {
public static void main(String[] args) {
Thread a1 = new Thread1("T1");
Thread a2 = new Thread1("T2");
a1.start();
a2.start();
}
}
輸出: T2:線程2Java靜態和線程安全
T1:線程2
T2:線程1
T1:線程2
T2:線程1
T1 :Thread2
T2:線程1
T1:線程2
T2:線程1
T1:線程1
什麼情況?爲什麼不能將數據用作同步化的?
也是一個很好的做法是鎖定對象'final'。 – Nikolay
優秀點。編輯。 –