【JAVA】String、StringBuilder、StringBuffer 。对此,小问号,你是不是有很多的朋友?

我们用的最多的是String,那跟它长得很像的这两位仁兄【StringBuilder、StringBuffer】又是啥来的呢?


      谈谈区别

      明明有了String为什么还要【StringBuilder、StringBuffer】?那是因为String赋值后就不能改变了,而在实际开发中常常有改动的需要,因此有了【StringBuilder、StringBuffer】。所以我们知道这两个是可变的字符串对象。

      那为什么又会有两个可变的呢?因为多线程编程的原因,容易导致数据不同步,出现数据错误的问题。而这时就需要一个StringBuffer来解决这个问题。那为什么不直接都用StringBuffer呢?因为StringBuffer需要做到同步,因此它速度比较慢(效率低)。所以我们需要一个“线程不安全,但效率高”的StringBuilder。

      于此,他们的区别我们已经了解了。是不是很通畅呢?不是?那看看下面的表格总结吧!

是否可变是否线程安全使用场景
String不可变安全(因为不可变),低效少量数据(因为每次操作都会重新生成String对象,又低效,又浪费空间)
StringBuffer可变安全,比较低效多线程大量数据
StringBuilder不安全,高效单线程大量数据

谈谈为什么线程安全

那为什么StringBuffer就线程安全了呢?让我们来看看源码吧~

     @Override
    public synchronized StringBuffer replace(int start, int end, String str) {
        toStringCache = null;
        super.replace(start, end, str);
        return this;
    }

发现StringBuffer里面的对字符串操作的方法都有 synchronized(同步)修饰。所以可以做到线程安全。


谈谈synchronized作用机制

这跟我们学过的【操作系统】里面的同步一个意思。

jvm里有相关的描述,描述如下:

Each object is associated with a monitor. A monitor is locked if and only if it has an owner. The thread that executes monitorenter attempts to gain ownership of the monitor associated with objectref, as follows:
• If the entry count of the monitor associated with objectref is zero, the thread enters the monitor and sets its entry count to one. The thread is then the owner of the monitor.
• If the thread already owns the monitor associated with objectref, it reenters the monitor, incrementing its entry count.
• If another thread already owns the monitor associated with objectref, the thread blocks until the monitor's entry count is zero, then tries again to gain ownership.

【百度翻译】

每个对象都与监视器关联。只有当监视器有所有者时,监视器才会被锁定。执行monitorner的线程尝试获得与objectref关联的监视器的所有权,如下所示:

•如果与objectref关联的监视器的条目计数为零,则线程将进入监视器并将其条目计数设置为1。线程就是监视器的所有者。

•如果线程已经拥有与objectref关联的监视器,它将重新进入监视器,并增加其条目计数。

•如果另一个线程已经拥有与objectref关联的监视器,则该线程将阻塞,直到监视器的条目计数为零,然后再次尝试获得所有权。

【自己理解】

就是有一个监视器,当有对象获取权限后,就标记有人了【条目计数(可接受对象个数)设置为0】,那其他对象申请时,就会被阻塞等待。只有当当前对象使用完,释放后。在阻塞队列中对象才能获取使用权限。

PS:秉持着联机学习 1+1>2的原则,欢迎大家指点批评,互相交流学习~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Q-CODER

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值