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?
source share