StringBuffer vs StringBuilder
我在上算法实现课。我的老师提到了StringBuffer和StringBuilder,他说StringBuffer比StringBuilder更安全,因为在线程方面。是真的吗?如果是,这意味着什么?我查过这个问题,很多答案都提到了同步。有人能解释这意味着什么,以及如何使StringBuffer比StringBuilder更安全吗?
从Java文档:
A thread-safe, mutable sequence of characters
同步是一个系统,用于同步线程对部分代码的访问,以便最多有一个线程可以执行同步块。
如果您的代码不是多线程的,或者只是如果您使用的
来自StringBuilder的JavaDoc:
A mutable sequence of characters. This class provides an API
compatible with StringBuffer, but with no guarantee of
synchronization. This class is designed for use as a drop-in
replacement for StringBuffer in places where the string buffer was
being used by a single thread (as is generally the case). Where
possible, it is recommended that this class be used in preference to
StringBuffer as it will be faster under most implementations.
由于它的所有方法都是同步的,这意味着即使您有100个线程(或更多)同时使用和修改它,它也将在处理其他请求之前完全执行每个操作。对于一个StringBuilder,你没有这样的保证。