简体   繁体   English

在Java中打印时,错误输出流与标准输出流并发

[英]Error output stream is concurrent with standard output stream when printing in Java

When this code gets executed, it produces scrambled outputs with no particular order between System.out.print() and System.err.print() . 执行此代码时,它会生成加扰输出,而System.out.print()System.err.print()之间没有特定顺序。 Why is that so? 为什么会这样?

for (int i = 0; i < 100; i++) {
    System.out.print(i+" ");
    System.err.print(i+"+");
}

Why is the standard error output stream is concurrent with standard output stream when printing in Java? 在Java中打印时,为什么标准错误输出流与标准输出流并发?

System.out and System.err are two different streams and so, they work at different times. System.outSystem.err是两个不同的流,因此,它们在不同的时间工作。 The problem you're experiencing here is because in console applications both streams are flushed to the same output buffer, which is the console. 您在这里遇到的问题是因为在控制台应用程序中,两个流都被刷新到相同的输出缓冲区,即控制台。 Each stream can flush at different time, the console buffer will care about the synchronization for you, but this leads to unpredictable results. 每个流可以在不同的时间刷新,控制台缓冲区将关心您的同步,但这会导致不可预测的结果。

If you want/need to have a single and better managed output for both streams, use a logger library like log4j2 or logback, that already solves these problems. 如果您希望/需要为两个流提供单个且更好的托管输出,请使用log4j2或logback之类的记录器库,它们已经解决了这些问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM