JDK API: StringBuilder This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
许多人吃完饭了,去盛一碗汤。
盛汤有几个步骤
1 把碗放在桌子上
2 拿起汤勺盛汤
3 把汤倒倒入碗里最典型的冲突就是
1 你拿了一个小碗(属性值比较较小,比如size=3)
2 你去盛汤
3 另一个也拿了一个大碗(比如size=8),因为一个类只有一个属性,所以你的碗被人替换掉了
4 你盛的汤倒入的,已经不再是你期望的那个碗了,当然倒入碗里后的结果也是不对的(不满或者溢出了)
StringBuilder不是线程安全的,它的运行速度比StringBuffer快.
线程不安全就是不同步的,但是速度快
java代码在编译的时候,会自动把安全的String转换为StringBuilder来处理,以提高效率
也可以说,如果单线程运行与多线程并行运行处理的结果都对,没有造成混乱那就说明是线程安全的。
StringBuilder
This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.
他只说 单线程用 StringBuilder,多线程用StringBuffered,更安全
看了这里的,我更加清楚了他们的区别~~哈哈
现在搞懂了,哈哈,感谢了!
以后要多来CSDN呢,能够学到很多东西呢!
StringBuilder是在JAVA 5.0里从C#搬过来的。习惯用StringBuffer的继续用就是,这个StringBuilder 是让c#转java的人员习惯的。
但是当多线程的时候StringBuffer比较安全
多线程中用StringBuilder
String a;
a+ new String()+new String
的效果差不多而且 编译器 自动把Stringa;a=a+newString();译成为
StringBuilder a ;
a.append(new String());