为什么有时会先打印System.err语句? [英] Why do System.err statements get printed first sometimes?

查看:156
本文介绍了为什么有时会先打印System.err语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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 通常不会被缓冲,因为错误消息需要立即打印。这是较慢的,但直觉是错误消息可能是时间关键的,因此程序减速可能是合理的。根据 Javadoc for 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:


通常,此流对应于主机环境或用户指定的显示输出或其他输出目标。 按照惯例,此输出流用于显示错误消息或应立即引起用户注意的其他信息,即使主要输出流(变量out的值)已重定向到通常不会持续监控的文件或其他目的地。

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 。例如,这一系列事件:

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语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆