有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是一个系统。出来默认情况下println线程安全?

System.out返回“标准”输出流-aPrintStream。{}的javadoc没有告诉我任何关于线程安全的信息,而是查看OpenJDK的源代码,OracleJDK告诉我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();
    }
}

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

所以我的问题是:

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

共 (1) 个答案

  1. # 1 楼答案

    由于PrintStream、它的超类FilterStream它的超类OutputStream的文档都没有提到任何关于线程安全或同步的内容,理论上你不能依赖它,它不是合同的一部分

    我认为如果有人生成了一个PrintStream类,而它在这方面没有像Oracle那样做,那将是非常令人惊讶的,但我以前也很惊讶