“的含义” StringBuilders不是线程安全的“ [英] Meaning of " StringBuilders are not thread safe"

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

问题描述

我已经阅读了一些关于 String StringBuilder 在Java程序设计语言中的优缺点的文章,In其中一篇文章,作者写道: StringBuilders不是线程安全的,所以在多线程中使用StringBuffer

I've read some articles about Strings and StringBuilders benefits and downsides in Java Programmming language, In one of the articles, the author wrote : StringBuilders are not Thread safe so in multiple threads use StringBuffer.

现在我无法理解那个意思。
你能否告诉我 Stirng StirngBuilder StringBuffer <的区别/ code>特别是在线程安全的上下文中。 (用代码描述可能非常好,但如果不可能,任何提示都会受到赞赏)。

Now I can't understand the meaning of that. Could you please show me the difference of Stirng, StirngBuilder and StringBuffer especially in the context of "Thread safety". (describing with code can be very good but if it is not possible, any hint will be appreciated).

推荐答案

如果有多个线程正在修改 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天全站免登陆