public class Demo05 {
public static void main(String[] args) {
new Thread(){
public void run() {
for (int i = 0; i < 10000; i++) {
StringBuilder s = new StringBuilder(); // 用StringBuilder打印的话, 黑马程序员和java会交错打印,可以试试,呵呵
System.out.print(s.append("黑"));
System.out.print(s.append("马"));
System.out.print(s.append("程"));
System.out.print(s.append("序"));
System.out.print(s.append("员"));
System.out.println("\r\n");
}
}
}.start();
new Thread(){
public void run() {
StringBuilder s = new StringBuilder();
for (int i = 0; i <10000; i++) {
System.out.println(s.append("j"));
System.out.println(s.append("a"));
System.out.println(s.append("v"));
System.out.println(s.append("a"));
System.out.println("\r\n");
}
}
}.start();
}
}作者: 蔚蓝小嗨 时间: 2013-4-27 20:52
StringBuilder是线程不同步的,如果多线程运行的话,会导致数据错乱。但是StringBuilder运行速度会比StringBuffer效率高作者: 403383221 时间: 2013-4-27 21:12
楼主可以看几段源码,这是StringBuffer的
public synchronized StringBuffer append(char[] str, int offset, int len) {
super.append(str, offset, len);
return this;
}
public synchronized StringBuffer append(boolean b) {
super.append(b);
return this;
}
public synchronized StringBuffer append(char c) {
super.append(c);
return this;
}
public synchronized StringBuffer append(int i) {
super.append(i);
return this;
}
这个是StringBuilder的
public StringBuilder append(char[] str, int offset, int len) {
super.append(str, offset, len);
return this;
}
public StringBuilder append(boolean b) {
super.append(b);
return this;
}
public StringBuilder append(char c) {
super.append(c);
return this;
}
public StringBuilder append(int i) {
super.append(i);
return this;
}
public StringBuilder append(long lng) {
super.append(lng);
return this;
}