微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

Java中,我注意到有时候,System.err语句首先在System.out语句之前打印,尽管后者首先出现在我的代码中.为什么?我很好奇.

解决方法

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

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

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.jb51.cc/java/126634.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐