0

I have the following code:

public static void main(String[] args) {
    final String s = "";
    Thread t = new Thread() {
        public void run() {
            try {
                Thread.currentThread().sleep(3000);
            } catch (InterruptedException ex) {
                System.out.println("111");
            }
            System.err.println("Waiting for s");
            synchronized (s) {
                System.err.println("got s");
            }
            System.out.println("last");
        }
    };

    t.start();
    synchronized (s) {
        t.interrupt();
        s.notifyAll();
    }


    try {
        Thread.currentThread()
              .sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("222");

}

The output is always:

111

last

Waiting for s

got s

222

Process finished with exit code 0

I don't understand how could the 'last' get printed before 'waiting for s' and 'got s'?? (why the lines are not executed sequentially?)

zaozaoer
  • 301
  • 3
  • 13
  • 5
    `System.out` and `System.err` are different output streams. They are not guaranteed to be interleaved in the console in the order they are written to. – Michael Sep 21 '20 at 22:36
  • Thank you for your comment. Yours makes since! I changed to all output to use System.out, and they print out sequentially. I guess I didn't know the root cause of this issue, I thought this was related to multi-threading – zaozaoer Sep 22 '20 at 15:39

0 Answers0