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 < 500; i++) {
stringBuffer.append(i/10);
//线程不安全的加上同步锁线程就安全了
// synchronized (this){
stringBuilder.append(i/10);
// }
}
}
}
}
结果
stringBuffer的长度2700
============
stringBuffer的长度2386
查看源代码
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;
}