0

我正在运行一些代码并期望将特定消息发送到 Systen.err 以在某一时刻出现,但由于某种原因它在另一时刻出现。这是代码 -

public static void main(String[] args) throws Exception {       
        System.out.println("File 1:");      
        for (NormalizedEntity ne : theSolution.entities.values()){
            System.out.println(ne);
        }

        System.out.println("\nFile 2:");
        for (NormalizedEntity ne : theSubmission.entities.values()){
            System.out.println(ne);
        }
        System.out.println(check());
    }

    static String check() {
        StringBuilder resultString = new StringBuilder();

        System.out.println("\nstarting check");
        for (NormalizedEntity solutionEntity : theSolution.entities.values()){
            NormalizedEntity submissionEntity = theSubmission.entities.get(solutionEntity.name);

            if(solutionEntity instanceof NormalizedClass){
                if(!(submissionEntity instanceof NormalizedClass)){
                    System.err.println("***WARNING: solutionEntity " + solutionEntity + "is a class but submissionEntity " + submissionEntity + " is not");//<---This line should be second to last
                    resultString.append("Expected " + submissionEntity + " to be a class called " + solutionEntity);
                }               
            }   

            //System.out.println("Found: " + ne + " in both");
        }
        return resultString.toString();
    }

这是输出 -

***WARNING: solutionEntity Class C {x=private int x, y=private int y} {C=C{1thParam=int, 2thParam=int}} {getX=int getX{}}is a class but submissionEntity null is not <--------- THIS LINE SHOULD BE AT THE END
File 1:
Class C {x=private int x, y=private int y} {C=C{1thParam=int, 2thParam=int}} {getX=int getX{}}
Class SubC {z=private int z} {} {}
C c
double d
int f{}
int i
SubC subC

File 2:
Class D {x=private int x, y=private int y} {D=D{1thParam=int, 2thParam=int}} {getX=int getX{}}
Class SubC {z=private int z} {} {}
D c
double d
int f{}
int i
SubC subC

starting check
Expected null to be a class called Class C {x=private int x, y=private int y} {C=C{1thParam=int, 2thParam=int}} {getX=int getX{}}

现在根据代码,输出的第一行应该是倒数第二行。但是,当我在 Eclipse 中运行它时,它会作为第一行出现。为什么是这样?我还注意到,如果我改变它System.errSystem.out它会按预期出现。所以看起来Eclipse首先收集所有错误输出然后处理标准输出?

4

1 回答 1

1

写入两个不同的流本来就容易出现乱序显示,但是,System.out.println 应该在每次调用时自动刷新,这意味着您看到的情况应该是不可能的,或者最坏的情况应该能够得到缓解与同步。

不幸的是,eclipse 中的一个错误实际上阻止了它正常工作并导致您看到的乱序行: 控制台中 System.out 和 System.err 之间的同步问题

您可能需要考虑使用诸如 logback 之类的日志框架(如果需要,还可以使用 SLF4J)来允许您记录不同级别的消息,同时保持一致的顺序。

于 2013-06-21T18:13:23.737 回答