Why use StringBuilder? StringBuffer can work with multiple thread as well as one thread?(为什么使用 StringBuilder?StringBuffer 可以与多个线程以及一个线程一起使用吗?)
问题描述
假设我们的应用程序只有一个线程.而我们正在使用 StringBuffer
那么有什么问题呢?
Suppose our application have only one thread. and we are using StringBuffer
then what is the problem?
我的意思是如果StringBuffer
可以通过同步处理多个线程,那么单线程工作有什么问题?
I mean if StringBuffer
can handle multiple threads through synchronization, what is the problem to work with single thread?
为什么要改用 StringBuilder
?
推荐答案
StringBuffers
是线程安全的,意味着它们有同步的方法来控制访问,因此只有一个线程可以访问 StringBuffer 对象的同步一次编码.因此,StringBuffer 对象通常可以安全地用于多线程环境中,其中多个线程可能试图同时访问同一个 StringBuffer 对象.
StringBuffers
are thread-safe, meaning that they have synchronized methods to control access so that only one thread can access a StringBuffer object's synchronized code at a time. Thus, StringBuffer objects are generally safe to use in a multi-threaded environment where multiple threads may be trying to access the same StringBuffer object at the same time.
StringBuilder 的
访问不同步,因此它不是线程安全的.通过不同步,StringBuilder 的性能可以优于 StringBuffer.因此,如果您在单线程环境中工作,使用 StringBuilder 而不是 StringBuffer 可能会提高性能.这也适用于其他情况,例如只有一个线程将访问 StringBuilder 对象的 StringBuilder 局部变量(即方法中的变量).
StringBuilder's
access is not synchronized so that it is not thread-safe. By not being synchronized, the performance of StringBuilder can be better than StringBuffer. Thus, if you are working in a single-threaded environment, using StringBuilder instead of StringBuffer may result in increased performance. This is also true of other situations such as a StringBuilder local variable (ie, a variable within a method) where only one thread will be accessing a StringBuilder object.
所以,更喜欢 StringBuilder
因为,
So, prefer StringBuilder
because,
- 性能提升小.
- StringBuilder 是 StringBuffer 类的 1:1 替代品.
- StringBuilder 不是线程同步的,因此在大多数 Java 实现上表现更好
看看这个:
- 不要使用StringBuffer!
- StringBuffer 与 StringBuilder 性能比较
这篇关于为什么使用 StringBuilder?StringBuffer 可以与多个线程以及一个线程一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么使用 StringBuilder?StringBuffer 可以与多个线程以及一个线程一起使用吗?


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 转换 ldap 日期 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01