Reputation: 926
I have the following code. Main thread starts another thread. After 7 seconds the main thread interrupts another thread.
package com.company;
public class Main {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
for ( int i = 0; i < 10; i++ )
{
System.out.println("Sleeping #" + i);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Interrupted");
e.printStackTrace();
continue;
}
}
}
});
t.start();
try {
Thread.sleep(7000);
t.interrupt();
} catch (InterruptedException e) {}
}
}
I expected to get such output:
Sleeping #0
Sleeping #1
Interrupted
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.company.Main$1.run(Main.java:16)
at java.lang.Thread.run(Thread.java:748)
Sleeping #2
Sleeping #3
... and so on
But what I get is:
Sleeping #0
Sleeping #1
Interrupted
Sleeping #2
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.company.Main$1.run(Main.java:16)
at java.lang.Thread.run(Thread.java:748)
Sleeping #3
... and so on
It first prints "Interrupted
". Then the output from the next iteration "Sleeping #2
", and then it prints stack trace. Why does it happen? It seems there is latency for printing stack trace. Is it IntelliJ Idea console related problem? Because when I run the program in a native console, it works well.
Upvotes: 0
Views: 48
Reputation: 2729
System.out.println
outputs to stdout
while Throwable.printStackTrace
outputs to stderr
. A terminal implementation may buffer each independently and the way the outputs of each stream will be interleaved is not well-defined.
If you want to ensure output from a given thread is displayed strictly sequentially, direct all output to the same stream. In your case, you can either change your printlns to use System.err
or use Throwable.printStackTrace(System.out)
Upvotes: 2