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。
新闻热点
疑难解答