What is the order of execution of newly created threads in java
Asked Answered
H

1

5
class Test {
    boolean isFirstThread = true;

    private synchronized void printer(int threadNo) {
        if(isFirstThread) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        isFirstThread = false;
        System.out.println(threadNo);
   }

   public void starter() {
        new Thread(){
            @Override()
            public void run() {
                printer(0);
            }
        }.start();

        new Thread(){
            @Override()
            public void run() {
                printer(1);
            }
        }.start();

        new Thread(){
            @Override()
            public void run() {
                printer(2);
            }
        }.start();

        new Thread(){
            @Override()
            public void run() {
                printer(3);
            }
        }.start();
    }
}

In the above code, when i call starter from main. I have created four new Threads to call a synchronized function. I know the order of execution of the threads can't be predicted. Unless they all wait for some time, so that first thread can finish and come out of the synchronized block. In which case I expect all threads to be held in a queue so i expected the answer as
0
1
2
3
But consistently(I ran the program more than 20 times) I was getting the output as
0
3
2
1
Which means that the threads are being held in a stack instead of a queue. Why is it so? Every answer in the google result says it is a queue but I am getting it as a stack. I would like to know the reason behind for holding the threads in stack(which is counter intuitive) instead of queue?

Hounding answered 22/4, 2016 at 19:16 Comment(3)
There is no defined order. Threads always run asynchronously, unless you provide proper synchronization.Tops
It depends on how the OS implements a mutex, note if you change you code, e.g. wait a much short time you could get a different result. try 2 millis instead of 2000Hawking
catb.org/jargon/html/N/nasal-demons.htmlTaffrail
S
10

The order in which threads start is up to the OS, it is not specified in the Java Language Spec. You call start in the main thread, but when the new thread gets allocated and when it begins processing its Runnable or run method is left to the OS' scheduler to decide.

Be careful not to rely on the order in which threads happen to start.

Stander answered 22/4, 2016 at 19:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.