String字符串常量
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence{
// private final char value[];
private final int count;
...
}
StringBuffer 字符串变量(线程安全)
public final class StringBuffer
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{
...
public synchronized StringBuffer append(StringBuffer sb) {
toStringCache = null;
super.append(sb);
return this;
}
/**
* @since 1.8
*/
@Override
synchronized StringBuffer append(AbstractStringBuilder asb) {
toStringCache = null;
super.append(asb);
return this;
}
...
}
StringBuilder 字符串变量(线程不安全)
public final class StringBuilder
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{
...
public StringBuilder append(StringBuffer sb) {
super.append(sb);
return this;
}
@Override
public StringBuilder append(CharSequence s) {
super.append(s);
return this;
}
...
}
abstract class AbstractStringBuilder implements Appendable, CharSequence {
...
/**
* The value is used for character storage.
*/
char[] value;
/**
* The count is the number of characters used.
*/
int count;
...
因为后两者继承AbstractStringBuilder ,所以其可变,而string 的count 是final的,所以是不可变的。
关于线程安全,我们可以看到Stringbuffer 的方法都用synchronized 同步方法,这样保证线程安全,而Stringbuilder 则没有
网友评论