同步:就是大家按照一定的规则访问(一般来说是FIFO); 异步:并发访问。从以上可以看来,同步/异步的问题只有在多线程下才会出现。来自java文档: String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved. 也就是说:StringBuffer 的所有方法是同步的,多线程访问下也是安全的。而String是非同步的,那是否可以说String就是不安全的呢?我的看法:String也是安全的,因为String的操作根本不会改变此字符串。
StringBuffer没有,还是Object的
StringBuffer则不一样,它指向的永远都是原来的那块内存地址
异步:并发访问。从以上可以看来,同步/异步的问题只有在多线程下才会出现。来自java文档:
String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved. 也就是说:StringBuffer 的所有方法是同步的,多线程访问下也是安全的。而String是非同步的,那是否可以说String就是不安全的呢?我的看法:String也是安全的,因为String的操作根本不会改变此字符串。
String s = "";
for(int i=0; i<10000; i++) {
s += "item" + i;
}
的运行需要10秒多,而:
StringBuffer sb = new StringBuffer();
for(int i=0; i<10000; i++) {
sb.append("item" + i);
}
基本上不需要什么时间。而数据量很大时就更加明显!!