什么是"StringBuilders不是线程安全的.意思是? [英] What does " StringBuilders are not thread-safe" mean?

查看:131
本文介绍了什么是"StringBuilders不是线程安全的.意思是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了一些有关Java编程语言中StringStringBuilder优缺点的文章.在其中一篇文章中,作者提到:

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.

不幸的是,我不明白这意味着什么.您能否解释一下StringStringBuilderStringBuffer之间的区别,尤其是在线程安全"的情况下.

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不是线程安全的.意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆