在java中System.out和System.err之间的竞争 [英] Race between System.out and System.err in java

查看:189
本文介绍了在java中System.out和System.err之间的竞争的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下java代码:

Please consider this java code:

public class CMain {
    public static void main(String[] args){

        for (int i = 0; i < 10; i++) {
            System.out.println("A");
            System.err.println("B");
        }

    }
}

快速查看代码,我们中的一些人可能认为输出必须是As和Bs的印刷品。然而不是!它是10个字符和10个B字符的随机外观。这样的事情:

By a quick look at the code, some of us may think the output has to be the print of As and Bs alternatively. However is not! It is a random appearance of 10 A characters and 10 B ones. Something like this:

为什么?什么是它的解决方案,以便As和Bs交替显示(A B A B A B ...)
在我提出这个问题之前,我检查了其他几个类似的问题以寻求解决方案,而不是为我的案例工作!我在这里带了一些:

Why is that? and what is the solution for it so that the As and Bs gets displayed alternatively ( A B A B A B ...) Before I ask this question, I checked several other similar questions for solution and non worked for my case! I have brought some of them here:

  • Synchronization and System.out.println
  • Java: synchronizing standard out and standard error
  • Java: System.out.println and System.err.println out of order PS. I am using Eclipse as my IDE

推荐答案

Why does this happen?

这是因为 out err 是两个不同的输出流。但是,它们都在控制台上打印。因此,您不会将它们视为不同的流。此外,当您执行 out.println()时,无法保证在语句执行后您将立即在控制台上看到输出。相反,字符串通常(取决于系统)存储在输出缓冲区中(如果你愿意),系统稍后处理它以将缓冲区的输出放到屏幕上。

This is because out and err are two different output streams. However, both of them print on console. So you do not see them as different streams. Moreover, when you do out.println(), it is not guaranteed that you will see the output on the console as soon as the statement gets executed. Instead, the strings are usually(depends on the system) stored in an output buffer (if you will) which is processed later by the system to put the output from the buffer onto the screen.

Solution :(

尽管如此 Eng.Fouad 指出您可以使用 setOut(System.err) setErr(System.out)为了让它们有序,当你实际把它放在一个应用程序中时,我仍然不建议这样做(仅用于调试目的)。

Although, as Eng.Fouad pointed out that you can use setOut(System.err) or setErr(System.out) to make them ordered, I would still not suggest doing that when you are actually putting this in an application (only use it for debugging purposes).

什么建议的解决方案是,最终只使用一个流来标准输出和标准错误,我认为这不是一件好事。

What the proposed solution does is that it will end up using only one stream for both the standard output and the standard error, which I do not think is a good thing to do.

这篇关于在java中System.out和System.err之间的竞争的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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