从源码看StringBuilder和StringBuffer

07-11 1786阅读

StringBuilder和StringBuffer

结论:StringBuilder是线程不安全的、StringBuffer是线程安全的

从源码看StringBuilder和StringBuffer
(图片来源网络,侵删)

StringBuilder和StringBuffer是比String高效的应为他是在原来的字符上进行增加的

public class StringBufferAndBuilder {
    static StringBuffer stringBuffer = new StringBuffer();
    static StringBuilder stringBuilder = new StringBuilder();
    public static void main(String[] args) {
        StringBufferAndBuilder main = new StringBufferAndBuilder();
        ThreadStringTest threadStringTest =  main.new ThreadStringTest();
        //创建3个线程加数据
        new Thread(threadStringTest).start();
        new Thread(threadStringTest).start();
        new Thread(threadStringTest).start();
        try {
            //等待4秒三个线程全部运行完
            Thread.sleep(4);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("stringBuffer的长度"+stringBuffer.length());
        System.out.println("============");
        System.out.println("stringBuffer的长度"+stringBuilder.length());
    }
    class ThreadStringTest implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i  

查看源代码

StringBuffer的append方法是使用了synchronized修饰
    @Override
    public synchronized StringBuffer append(int i) {
        toStringCache = null;
        super.append(i);
        return this;
    }
StringBuilder的append方法没有同步代码块所以线程不安全
    @Override
    public StringBuilder append(int i) {
        super.append(i);
        return this;
    }
VPS购买请点击我

文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。

目录[+]