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
优秀点。编辑。 –