考虑以下代码:
Thread t1 = new Thread(() -> {
System.out.println("t1 running");
System.err.println("foo 1");
});
Thread t2 = new Thread(() -> {
System.out.println("t2 running");
System.out.println("foo 2");
});
Thread t3 = new Thread(() -> {
System.out.println("t3 running");
System.out.println("foo 3");
});
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
上面的所有线程都应该顺序执行,因为我并没有一次启动所有线程,并且我确实在每个启动中启动所有线程,以阻止主线程的执行,直到执行每个主线。
我期望以下原子输出:
t1 running
foo 1
t2 running
foo 2
t3 running
foo 3
但这是实际的结果,这确实使我感到困惑:
t1 running
t2 running
foo 2
t3 running
foo 3
foo 1
就我而言,唯一的原因是,如果还有另一个线程为 System.err创建在引擎盖打印“ Foo 1”下。请为我启发这种行为的真正原因。
Consider the following code:
Thread t1 = new Thread(() -> {
System.out.println("t1 running");
System.err.println("foo 1");
});
Thread t2 = new Thread(() -> {
System.out.println("t2 running");
System.out.println("foo 2");
});
Thread t3 = new Thread(() -> {
System.out.println("t3 running");
System.out.println("foo 3");
});
t1.start();
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
All of the threads above is supposed to execute sequentially since I'm not starting them all at once and I do call Thread.join() on each of them to block the main thread from executing until each has been executed.
I'd expect the following atomic output:
t1 running
foo 1
t2 running
foo 2
t3 running
foo 3
But this is the actual result, which does kind of confuse me:
t1 running
t2 running
foo 2
t3 running
foo 3
foo 1
As far as I'm concerned the only possible reason for that would be if there was another thread created for System.err under the hood printing "foo 1". Please do enlighten me on what is the real cause for such behaviour.
发布评论
评论(1)
当然,代码顺序执行,您可以检查此(而不是通过在不同流中检查日志订单!):
output:
请注意,
out
和er
err streams可以被不同地冲洗(就我而言,我在终端运行此代码时会看到正确的预期顺序,但是在Intellij中运行时,我会看到不正确的顺序,请参见这个)of course the code executes sequentially, you can check this(not by checking logs order in different streams!):
output:
note that the
out
anderr
streams can being flushed differently (in my case I see the correct expected order when I run this code in terminal, but I see the incorrect order when I run in IntelliJ, see this)