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的原则,欢迎大家指点批评,互相交流学习~

原创文章 17 获赞 4 访问量 5189

猜你喜欢

转载自blog.csdn.net/yqq577/article/details/105175082