加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 00:10:50 所属栏目:Java 来源:网络整理
导读:在 Java中,我注意到有时候,System.err语句首先在System.out语句之前打印,尽管后者首先出现在我的代码中.为什么?我很好奇. 解决方法 通常,System.out是缓冲的输出流,因此文本在被刷新到目标位置之前被累积.这可以显着提高打印大量文本的应用程序的性能,因为
在 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中.

希望这可以帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读