Strange exit when starting the loop

Can anyone tell me why I always have this weird result after running this loop? Is this a threading issue or what?

  for(int i=0;i<10;i++){
     System.out.println("out: "+i);
     System.err.println("err: "+(i+1));



    err: 1
    out: 0
    err: 2
    err: 3
    err: 4
    out: 1
    out: 2
    out: 3
    out: 4
    err: 5
    out: 5
    err: 6
    out: 6
    err: 7
    err: 8
    out: 7

    out: 8
    err: 9
    out: 9
    err: 10
    out: 10



source to share

2 answers

Your terminal launches your application and has two file descriptors connected to it, one for stdout and one for stderr. It then has to read the data that your application writes to these file descriptors and prints to the screen. There is no guarantee how the terminal application (or OS, for that matter) implements this interaction. Imagine that the terminal actually has 2 streams that are read from stdout and stderr in parallel. The order in which these 2 threads will receive data from fds and to screen is not guaranteed to be consistent when your application exits.



Standard output and standard error have separate buffers. Interleaving is normal. Try flushing the output stream after every print call. In the meantime, there is no need to worry about it. ”



All Articles