实例分析StringBuffer和StringBuilder的区别及使用场景

前言

学过Java的我们都知道, StringBuffer是线程安全的, StringBuilder是线程不安全的, 为什么StringBuffer是线程安全的,对于此问题,相信不少人也都知道一些,因为StringBuffer类中有用synchronized关键字修饰,但它们的用法区别在哪呢

示例

运行以下代码,看一下区别

  • 多线程中

    public class Test {
        public static void main(String[] args) throws InterruptedException {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < 10000; i++){
                new Thread(() -> {
                    for (int j = 0; j < 1000; j++){
                        stringBuilder.append("a");
                    }
                }).start();
            }
    
            Thread.sleep(100L);
            System.out.println("stringBuilder: " + stringBuilder.length());
            System.out.println("-----------------------");
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < 10000; i++){
                new Thread(() -> {
                    for (int j = 0; j < 1000; j++){
                        stringBuffer.append("a");
                    }
                }).start();
            }
    
            Thread.sleep(100L);
            System.out.println("StringBuffer: " + stringBuffer.length());
        }
    }
    
    >>> StringBuilder: 9930128
    >>> ----------------------
    >>> StringBuffer: 10000000
    
  • 单线程中

    public class test {
        public static void main(String[] args) {
        	long time = System.currentTimeMillis();
        	StringBuilder stringBuilder = new StringBuilder();
        	for (int i = 0; i < 10000; i++) {
        		for (int j = 0; j < 1000; j++) {
        			stringBuilder.append("a");
        		}
        	}
        	long timeDiff = System.currentTimeMillis() - time;
        	System.out.println("StringBuilder: " + stringBuilder.length() + " " + timeDiff);
    
        	System.out.println("-----------------------");
    
        	time = System.currentTimeMillis();
        	StringBuffer stringBuffer = new StringBuffer();
        	for (int i = 0; i < 10000; i++) {
        		for (int j = 0; j < 1000; j++) {
        			stringBuffer.append("a");
        		}
        	}
        	timeDiff = System.currentTimeMillis() - time;
        	System.out.println("StringBuffer: " + stringBuffer.length() + " " + timeDiff);
        }
    }
    
    >>> StringBuilder: 10000000 144
    >>> -----------------------
    >>> StringBuffer: 10000000 295
    

分析

  • 在多线程操作中,由于StringBuilder线程不安全,会导致数据混乱,因此,多线程操作中优选StringBuffer
  • 在单线程操作中,StringBuilder的速度优于StringBuffer。此时优选StringBuilder

你可能感兴趣的:(JAVA)