import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
public class StringBuilderAndBufferTest implements Runnable{ static StringBuilder builder = new StringBuilder(); static StringBuffer buffer=new StringBuffer();
public void run() { try { Thread.sleep((int)(Math.random() * 2)); } catch (InterruptedException e) { e.PRintStackTrace(); } builder.append("1"); buffer.append("1");}public static void main(String[] args) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(50); for (int i = 0; i < 30000; i++) { pool.execute(new StringBuilderAndBufferTest()); } Thread.sleep(3000); // 如果長度為30000就是安全的 System.out.println("StringBuilder長度==="+builder.length()); System.out.println("StringBuffer長度==="+buffer.length());}}
結果如下:
StringBuilder長度===29536StringBuffer長度===30000
查看二者append()方法的區別
public StringBuilder append(String str) { super.append(str); return this;}public synchronized StringBuffer append(String str) { super.append(str); return this;}public AbstractStringBuilder append(String str) { if (str == null) str = "null"; int len = str.length(); ensureCapacityInternal(count + len); str.getChars(0, len, value, count); count += len; return this;}二者底層都是調用父類AbstractStringBuilder的append(String str),區別在于StringBuffer的append方法有synchronized關鍵字。synchronized關鍵字表示該方法一次只能有一個線程進入,其他線程要想在此時調用該方法,只能排隊等候,當前線程(就是在synchronized方法內部的線程)執行完該方法后,別的線程才能進入
故可知:
StringBuilder是非線程安全的,效率更高;
StringBuffer是線程安全的,效率不如StringBuilder。
新聞熱點
疑難解答