Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codes on the same thread executed in unusual order

This is a piece of code in a SCJP practice question:

public class Threads2 implements Runnable {

    public void run() {
        System.out.println("run.");
        throw new RuntimeException("Problem");
    }

    public static void main(String[] args) {
        Thread t = new Thread(new Threads2());
        t.start();
        System.out.println("End of method.");
    }
}

It was partly mentioned here.

However, my question is not the prior question. As I run the program on a few machines multiple times, I occasionally get RuntimeException before "run" in the output. This does not make sense to me, as these lines of codes executed in the same thread, so it should have been the reverse order.

Can anyone explain why that happens?

like image 909
kwkt Avatar asked Nov 11 '22 04:11

kwkt


1 Answers

e.printStacktrace is using System.err.

System.out and System.err are different object. It has Buffered writer to display to client window.

Even it will execute in different order , it will go to different Buffer.

If Err buffer prints first err will come first.Otherwise out will come first.

like image 162
Siva Kumar Avatar answered Nov 15 '22 07:11

Siva Kumar