java String对象作为线程对象锁
假设有两个string对象:
String s1 = new String("abc");
String s2 = new String("abc");
直接用来做线程对象锁是不行的:
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s1){
while(true){
System.out.println("s1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s2){
while(true){
System.out.println("s2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
输出结果:
s1
s2
s1
s2
s1
说明根本没锁住。
加上intern()之后,再试:
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s1.intern()){
while(true){
System.out.println("s1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
synchronized (s2.intern()){
while(true){
System.out.println("s2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
输出结果是,要么只能输出s1,要么只能输出s2,说明这次确实锁住了。
浙公网安备 33010602011771号