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 :スレッド2
T2:スレッド1
T1:スレッド2
T2:スレッド1
T1:スレッド1
状況は何ですか?データを同期化して使用できないのはなぜですか?
また、ロックオブジェクトを「最終」にすることをお勧めします。 – Nikolay
優れたポイント。編集されました。 –