java是一个系统。出来默认情况下println线程安全?
System.out
返回“标准”输出流-aPrintStream
。{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()
从未创建“混合”输出
所以我的问题是:
- 我可以依赖这种行为(使用不同的jvm)吗李>
- 我有没有遗漏一些描述这种行为的文档李>
# 1 楼答案
由于
PrintStream
、它的超类FilterStream
和它的超类OutputStream
的文档都没有提到任何关于线程安全或同步的内容,理论上你不能依赖它,它不是合同的一部分我认为如果有人生成了一个
PrintStream
类,而它在这方面没有像Oracle那样做,那将是非常令人惊讶的,但我以前也很惊讶