System.out.println默认是线程安全的吗?

Tob*_*iSH 5 java openjdk multithreading

System.out返回"标准"输出流 - a PrintStream.该javadoc的PrintStream告诉我任何关于线程安全的,但看源的OpenJDKOracleJDK告诉我,println是同步的.

/**
 * Prints a String and then terminate the line.  This method behaves as
 * though it invokes <code>{@link #print(String)}</code> and then
 * <code>{@link #println()}</code>.
 *
 * @param x  The <code>String</code> to be printed.
 */
public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

这非常适合我的经验:System.out.println()从不同的线程调用时,调用从未创建"混合"输出.

所以我的问题:

  1. 我可以依赖这种行为(使用不同的JVM)吗?
  2. 是否有一些我遗漏的文档描述了这种行为?

T.J*_*der 6

由于的文件PrintStream,它的父FilterStream,和它的超类OutputStream都不能说的线程安全性或同步任何东西,在理论上讲,你不能依赖它,它不是合同的一部分.

我认为,如果有人制作的课程没有甲骨文在这方面所做的那样,那将是令人惊讶的PrintStream,但我之前感到惊讶.