What is the execution order of newly created threads in java

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 the starter from the main one. I created four new threads to call a synchronized function. I know that thread execution order cannot be predicted. If they all do not wait for a while, so the first thread can end and exit the synchronized block. In this case, I expect all threads to be queued, so I was expecting a response like
0
1
2
3
But sequentially (I ran the program more than 20 times) I got the output as
0
3
2
1
This means that threads are stored on the stack instead of the queue. Why is this so? Every answer in the Google results says it's a queue, but I get it as a stack. I would like to know the reason why keeping threads on the stack (which is intuitive) instead of a queue?

+5
source share
1 answer

The order in which threads are started depends on the OS; it is not specified in the Java Language Spec. You call the start on the main thread, but when a new thread gets allocated and when it starts to process, its Runnable or run method remains for the OS scheduler to decide.

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

+10
source

Source: https://habr.com/ru/post/1247748/


All Articles