public class StringSyncTest {
public static void main(String[] args) {
StringEx stringEx = new StringEx();
StringAThread stringAThread = new StringAThread(stringEx);
stringAThread.setName("A");
StringBThread stringBThread = new StringBThread(stringEx);
stringBThread.setName("B");
stringAThread.start();
stringBThread.start();
}
}
class StringEx{
public void run(String string){
synchronized (string){
while (true){
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class StringAThread extends Thread {
StringEx stringEx;
String str = "Str";
public StringAThread(StringEx stringEx){
this.stringEx = stringEx;
}
@Override
public void run() {
stringEx.run(str);
}
}class StringBThread extends Thread {
StringEx stringEx;
String str = "Str";
public StringBThread(StringEx stringEx){
this.stringEx = stringEx;
}
@Override
public void run() {
stringEx.run(str);
}
}
执行结果
B
B
B
B
B
B
B
B
B
两个String的值一致时指向的地址是一致的,其实两个线程锁的是同一个对象。而在实际工作中,String值相同的情况时有发生,而出现问题有不容易发现。