synchronized 为什么不能使用string对象而是要使用string.intern

先看代码:

/**
* Created by Jarvis.y on 2020/11/5
*/
public class StringTest {


    public static void main(String[] args) {
        String s1 = "Jarvis.y";
        String s2 = new String("Jarvis.y");
        System.out.println(s1.equals(s2));
        System.out.println(System.identityHashCode(s1));
        System.out.println(System.identityHashCode(s2));
        System.out.println(System.identityHashCode(s1.intern()));
        System.out.println(System.identityHashCode(s2.intern()));
    }
}

运行效果:

true
1870252780
1729199940
1870252780
1870252780

结论:
1、String 重写了equals 方法。所以不同对象但是值相等的时候在equals比较也会返回true,但是hashcode 不一定会相等。
2、synchronized 锁的是对象,这个时候string值相同,但是不同对象,所以就无法锁住。
3、所以使用String 的时候需要使用intern方法。intern是一个 native 的方法,如果常量池中存在当前字符串, 就会直接返回当前字符串. 如果常量池中没有此字符串, 会将此字符串放入常量池中后,再返回,因此intern每次返回同一个对象。这个时候使用synchronized 就可以锁住了。

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值