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,说明这次确实锁住了。


posted @ 2020-07-14 16:01  java12345_com  阅读(484)  评论(0)    收藏  举报