问题描述
在Java中,我注意到有时会在 System.out
语句之前首先打印 System.err
语句,虽然后者在我的代码中首先出现在前者之前。为什么?我很好奇。
In Java, I noticed that sometimes, System.err
statements get printed first before System.out
statements, although the latter appears first before the former in my code. Why? I'm curious.
推荐答案
通常情况下, System.out
是一个缓冲输出流,因此文本在刷新到目标位置之前会累积。这可以显着提高打印大量文本的应用程序的性能,因为它可以最大限度地减少必须进行的昂贵系统调用的次数。但是,这意味着文本并不总是立即显示,并且可能比它写入的时间晚得多。
Typically, System.out
is a buffered output stream, so text is accumulated before it is flushed to the destination location. This can dramatically improve performance in applications that print large amounts of text, since it minimizes the number of expensive system calls that have to be made. However, it means that text is not always displayed immediately, and may be printed out much later than it was written.
System.err 通常不会被缓冲,因为错误消息需要立即打印。这是较慢的,但直觉是错误消息可能是时间关键的,因此程序减速可能是合理的。根据:
System.err
, on the other hand, typically is not buffered because error messages need to get printed immediately. This is slower, but the intuition is that error messages may be time-critical and so the program slowdown may be justified. According to the Javadoc for System.err
:
(我的重点)
但是,因此,发送到
System.out
的旧数据可能会在较新的 System.err 消息,因为旧的缓冲数据的刷新晚于消息发送到
System.err
。例如,这一系列事件:
However, as a result, old data sent to
System.out
might show up after newer System.err
messages, since the old buffered data is flushed later than the message was sent to System.err
. For example this sequence of events:
- Hello,缓冲到
System.out
- PANIC直接发送到
System.err
并立即打印。 - 世界!缓冲到
System.out
,并打印缓冲数据
"Hello," is buffered to
System.out
"PANIC" is sent directly to
System.err
and is printed immediately." world!" is buffered to
System.out
, and the buffered data is printed
结果输出
PANIC
Hello, world!
即使
Hello
打印到 System.out
之前 PANIC
打印到 System.err
。
Even though
Hello
was printed to System.out
before PANIC
was printed to System.err
.
希望这会有所帮助!
这篇关于为什么有时会先打印System.err语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!