java – 为什么有时会首先打印System.err语句?

前端之家收集整理的这篇文章主要介绍了java – 为什么有时会首先打印System.err语句?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Java中,我注意到有时候,System.err语句首先在System.out语句之前打印,尽管后者首先出现在我的代码中.为什么?我很好奇.

解决方法

通常,System.out是缓冲的输出流,因此文本在被刷新到目标位置之前被累积.这可以显着提高打印大量文本的应用程序的性能,因为它可以最大限度地减少必须进行昂贵的系统调用次数.但是,这意味着文本并不总是立即显示,并且可能会比写入的时间稍晚打印出来.

另一方面,System.err通常不会缓冲,因为错误消息需要立即打印.这是较慢的,但是直觉是错误消息可能是时间关键的,因此程序减速可能是合理的.根据@L_404_1@:

Typically this stream corresponds to display output or another output destination specified by the host environment or user. By convention,this output stream is used to display error messages or other information that should come to the immediate attention of a user even if the principal output stream,the value of the variable out,has been redirected to a file or other destination that is typically not continuously monitored.

(我的重点)

但是,因此,发送到System.out的旧数据可能会在较新的System.err消息之后出现,因为旧的缓冲数据比消息发送到System.err稍后刷新.例如这个事件序列:

>“Hello”,缓冲到System.out
>“PANIC”直接发送到System.err并立即打印.
>“世界!”缓冲到System.out,并打印缓冲的数据

会导致输出

PANIC
Hello,world!

即使在PANIC打印到System.err之前,Hello被打印到System.out中.

希望这可以帮助!

原文链接:https://www.f2er.com/java/126634.html

猜你在找的Java相关文章