两者都是针对可变字符串,String针对不可变字符串
StringBuffer
线程安全,效率低
StringBuilder
线程不安全,效率高
工作上在方法内部使用字符串构建时比较常用StringBuilder
代码验证线程安全性实例
public class StringThreadTest {
public static void main(String[] args) throws InterruptedException {
StringBuffer buffer = new StringBuffer();
Thread[] threads = new Thread[20];
for (int i = 0; i < 20; i++) {
threads[i] = new Thread(()->{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int j = 0; j < 10; j++) {
buffer.append(j);
}
});
threads[i].start();
}
for (int i = 0; i < 20; i++) {
threads[i].join();
}
System.out.println("buffer -> " + buffer);
System.out.println("buffer len ->" + buffer.length());
StringBuilder builder = new StringBuilder();
Thread[] threads2 = new Thread[20];
for (int i = 0; i < 20; i++) {
threads2[i] = new Thread(()->{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int j = 0; j < 10; j++) {
builder.append(j);
}
});
threads2[i].start();
}
for (int i = 0; i < 20; i++) {
threads2[i].join();
}
System.out.println("builder -> " + builder);
System.out.println("builder len ->" + builder.length());
}
}
可能结果:
buffer -> 01021324354657687989012345678901234051627384956789001122334455667788990012314253041021324354550617283945678967896789061728394567890011223344567895678901234567890123456071829345678901234567890123456789
buffer len ->200
builder -> 0123456789012345012345678923456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012340912340678934567890123456789
builder len ->187
正常情况下构建的是200个字符的字符串,StringBuffer线程安全正常,StringBuilder线程不安全不正常!