public class RedirectTest { public static void main(String args[]){ System.out.println("hello normal"); System.setOut(System.err); System.out.println("hello error"); //System.out.println("hello error1"); } }
對於以上代碼有時候輸出 java
hello normal hello error
有時 dom
hello error hello normal
緣由 this
I believe this is because you are writing to two different outputs (one is standard out and the other standard error). These are probably handled by two different threads at runtime to allow writing to both during java execution. Assuming this is the case, the cpu task scheduler is not going to execute the threads in the same order every time. spa
You should never get this functionality if all of your output is going to the same output stream (ie everything goes to standard out or everything goes to standard err). You will never be guaranteed execution order of standard error vs standard output. code
No need to talk about two different threads... the key is that standard output and error are distinct streams here :-) orm
http://stackoverflow.com/questions/12594537/random-printing-order-for-system-out-system-err-calls get