Java + Eclipse:同步标准输出和标准错误

2022-01-22 00:00:00 synchronization java eclipse stdio

我使用 Eclipse.当我有这样的应用程序时:

I use Eclipse. When I have an application like this:

write 20 times 'Hello World
' to stdout
write 'ERROR
' to stderr
write 5 times 'Hello  World
' to stdout

输出多次看起来像这样:

The output looks many times like this:

Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
...
Hello World
Hello World
Hello World
ERROR

有没有办法同步这两个输出流?当然不需要在 20 次 Hello World 块后等待几毫秒,在打印 ERROR 后等待几毫秒.

Is there a way to synchronize these two output streams? Of course without waiting a few milliseconds after the block of 20 times Hello World and waiting a few milliseconds after printing ERROR.

推荐答案

信不信由你,冲洗在这里不是解决方案......

如果流导致由底层操作系统提供的抽象"(例如磁盘驱动器或控制台),则剩余字节将传递给操作系统进行写入;它不保证它们确实被写入......."(请参阅 OutputStream 文档).这里的关键是,如果操作系统愿意,它可以以不同的顺序处理来自不同流的刷新.

Believe it or not, flushing is not a solution here....

If a stream leads to "an abstraction provided by the underlying operating system" (e.g. a disk drive or console) then remaining bytes "are passed to the operating system for writing; it does not guarantee that they are actually written..." (see the OutputStream documentation). The key here is that the OS can handle flushes from different streams in different orders if it so chooses.

我刚刚在我的程序中发生了这种情况.我在两条正常消息之间出现了一条错误消息,这两条消息在错误消息出现之前都已刷新.

I just had this happen in my program. I had an error message appear between two normal message, both of which had flushed before the error message did.

所以问题仍然存在,有没有一种内置的方式来同步两个流?还是我们必须手动处理?

So the question remains, is there a built-in way to synchronize two streams? Or do we have to handle that manually?

相关文章