我已经阅读了一些有关Java编程语言中String和StringBuilder优缺点的文章.在其中一篇文章中,作者提到:
I have read some articles about the pros and cons of String and StringBuilder in the Java Programming language. In one of the articles, the author mentioned that:
StringBuilder 不是线程安全,因此在多线程中使用 StringBuffer .
StringBuilder is not Thread-safe, so in multiple threads use StringBuffer.
不幸的是,我不明白这意味着什么.您能否解释一下String,StringBuilder和StringBuffer之间的区别,尤其是在线程安全"的情况下.
Unfortunately, I cannot understand what it means. Could you please explain the difference between String, StringBuilder and StringBuffer especially in the context of "Thread safety".
如果您能用代码示例进行描述,我将不胜感激.
I would appreciate it if you could describe with the code example.
推荐答案如果多个线程正在修改StringBuilder的同一实例,则结果可能是意外的-即某些修改可能会丢失.这就是为什么在这种情况下应使用StringBuffer的原因.但是,如果每个线程StringBuilder实例只能由一个线程修改,则最好使用StringBuilder,因为这样效率更高(线程安全性会带来性能成本).
If multiple threads are modifying the same instance of a StringBuilder, the result can be unexpected - i.e. some of the modifications may be lost. That's why you should use StringBuffer in such situations. If, however, each thread StringBuilder instance can be modified by only one thread, it is better to use StringBuilder, since it would be more efficient (thread safety comes with a performance cost).
更多推荐
什么是"StringBuilders不是线程安全的.意思是?
发布评论