
10

String str="abc" 一定会进入到字符串常量池吗?
source link: https://www.v2ex.com/t/788338
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

String str="abc" 一定会进入到字符串常量池吗?
String str="abc" 一定会进入到字符串常量池吗?
如果一定会,为什么我对 str 加锁,锁并没有用。
6 条回复 • 2021-07-08 20:25:59 +08:00
Yimkong 12 小时 17 分钟前 via iPhone
锁是加给对象的,你这个每次加锁都是都会锁一个新的 String 对象。
String str=new String("abc"),锁这个就行
String str=new String("abc"),锁这个就行
Cy1 12 小时 11 分钟前 1
你是怎么加锁的?
public static void main(String[] args) {
String lock1 = "abc";
String lock2 = "abc";
new Thread(() -> {
synchronized (lock1) {
System.out.println("t1");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t1").start();
new Thread(() -> {
synchronized (lock2) {
System.out.println("t2");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t2").start();
}
其中一个线程会被阻塞,明显就是锁的是同一个对象,所以会进 字符串常量池
public static void main(String[] args) {
String lock1 = "abc";
String lock2 = "abc";
new Thread(() -> {
synchronized (lock1) {
System.out.println("t1");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t1").start();
new Thread(() -> {
synchronized (lock2) {
System.out.println("t2");
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t2").start();
}
其中一个线程会被阻塞,明显就是锁的是同一个对象,所以会进 字符串常量池
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK