Java:同步标准输出和标准错误 [英] Java: synchronizing standard out and standard error

查看:188
本文介绍了Java:同步标准输出和标准错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,如果我可以解决它会很好。为了调试目的(以及其他一些事情),我正在标准输出上编写一个控制台Java应用程序的日志。一些标准化的东西,一些错误的东西打印在标准错误。问题是这两个不完全同步,所以打印行的顺序并不总是正确的。我猜这是因为很多东西都被打印出来,一个输出的缓冲区已经满了,所以其他的输出在第一个输出缓冲区之前打印。



例如,我想写这个:

  syso:aaa 
syso:bbb
syso:ccc
syso:ddd
syso:eee
syserr:---

什么有时打印的是

  aaa 
bbb
ccc
---
ddd
eee

有时候两者之间没有新的一行, / p>

  aaa 
bbb
ccc ---

ddd
eee

每当我在输出上打印某些东西时,我用

  System.out.flush(); 

  System.err.flush(); 

如何解决这个问题?
Btw,一切都打印在Eclipse控制台中。

解决方案

  public class Util 

synchronized public static void printToOut(...)
out.print(...)

synchronized public static void printToErr(...)
err.print(...)


I have a strange problem and it would be nice if I could solve it. For the debugging purposes (and some other things, as well) I'm writing a log of a console Java application on the standard output. Some things that are writen on standard out, and some things like errors are printed on standard error. The problem is that these two are not perfectly synchronized, so the order of printed lines is not always correct. I guess this is because many things are printed and it happens that a buffer for one output is full so the other output prints before the first one flushes it buffer.

E.g., I want to write this:

syso: aaa
syso: bbb
syso: ccc
syso: ddd
syso: eee
syserr: ---

What is sometimes printed is

aaa
bbb
ccc
---
ddd
eee

Sometimes there is not a new line in between, so it looks like

aaa
bbb
ccc---

ddd
eee

Every time I print something on an output, I flush the same output with

System.out.flush();

or

System.err.flush();

How to solve this problem? Btw, everything is printed in the Eclipse console.

解决方案

public class Util

    synchronized public static void printToOut(...)
        out.print(...)

    synchronized public static void printToErr(...)
        err.print(...)

这篇关于Java:同步标准输出和标准错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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