5

String str="abc" 一定会进入到字符串常量池吗?

 3 years ago
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.
neoserver,ios ssh client
String str="abc" 一定会进入到字符串常量池吗?

V2EX  ›  程序员

String str="abc" 一定会进入到字符串常量池吗?

  kikione · 12 小时 44 分钟前 · 1006 次点击

String str="abc" 一定会进入到字符串常量池吗?

如果一定会,为什么我对 str 加锁,锁并没有用。

6 条回复    2021-07-08 20:25:59 +08:00

Yimkong

Yimkong   12 小时 17 分钟前 via iPhone

锁是加给对象的,你这个每次加锁都是都会锁一个新的 String 对象。
String str=new String("abc"),锁这个就行

huang119412

huang119412   12 小时 13 分钟前

字符串字面量一定进常量池,常量池的字符串不一定不会被回收,synchronized 锁住的对象,当然可以锁住字符串常量对象

Cy1

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();
}
其中一个线程会被阻塞,明显就是锁的是同一个对象,所以会进 字符串常量池

lululau

lululau   12 小时 9 分钟前

都在背面试题吗😂

3dwelcome

3dwelcome   11 小时 16 分钟前

java 判断是不是一个对象,直接相等就可以了,都不用上锁。

如果进字符串常量池,就会相等。

关于   ·   帮助文档   ·   FAQ   ·   API   ·   我们的愿景   ·   广告投放   ·   感谢   ·   实用小工具   ·   910 人在线   最高记录 5497   ·  

创意工作者们的社区

World is powered by solitude

VERSION: 3.9.8.5 · 18ms · UTC 21:39 · PVG 05:39 · LAX 14:39 · JFK 17:39
♥ Do have faith in what you're doing.


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK