同步如何在StringBuffer中工作?

时间:2016-05-14 16:19:28

标签: java multithreading synchronization stringbuffer

我一直读到StringBuffer是线程安全的,但我从来没有理解它是如何实现的。我在文档中的方法定义中没有看到任何synchronized关键字。 Java是否使用synchronized块?所有方法都是synchronized吗?我相信只有更新底层对象的方法应该是synchronized

2 个答案:

答案 0 :(得分:0)

  

字符串缓冲区可供多个线程使用。这些方法在必要时进行同步,以便任何特定实例上的所有操作都表现得好像它们以某种顺序发生,这与所涉及的每个单独线程所进行的方法调用的顺序一致。

请参阅https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html

如果您对如何详细实现它感兴趣,请使用源代码安装Oracle JDK并直接查看StringBuffer.java或look here for an Apache Licensed online version

答案 1 :(得分:0)

StringBuffer是线程安全的。 append方法已同步。

查看here了解更多详情。



/**
 * A thread-safe, mutable sequence of characters.
 * A string buffer is like a {@link String}, but can be modified. At any
 * point in time it contains some particular sequence of characters, but
 * the length and content of the sequence can be changed through certain
 * method calls.
 * <p>
 * String buffers are safe for use by multiple threads. The methods
 * are synchronized where necessary so that all the operations on any
 * particular instance behave as if they occur in some serial order
 * that is consistent with the order of the method calls made by each of
 * the individual threads involved.
&#13;
&#13;
&#13;

public synchronized StringBuffer append(Object obj) {
    super.append(String.valueOf(obj));
    return this;
}

public synchronized StringBuffer append(String str) {
    super.append(str);
    return this;
}

编辑:

关于

的查询
  

如果在更新期间调用getChars()会发生什么,它会返回旧值还是到目前为止更新的内容?

答案是:

getChars()将等待其他同步方法完成执行并释放锁定。

如果您参考文档的第二段,它明确指出操作的行为就像它们按顺序发生一样。