The output coming for me is: 342. Note that 3 & 4 come together instantly, then after two seconds gap, 2 is displayed.
My doubts is that first x.start() is executed on Line 19, which should ideally execute the run() definition of the anonymous inner class from Line 12-16. There since x is the current object, it should fall asleep for two seconds and then display the output as 2.
After that y.start() is executed and x.wait() throws exception since it is not the current object, hence 34 should be displayed.
So output in my knowledge should be a two second pause followed by 234. But it's not!
Also if I reversed Line 19 and 20 the output is still the same.
If anyone could explain why the opposite is happening? Thanks in advance.
No it does not happen that way. you create 2 threads and then you start them as
so what happens is that main thread(which is the one that is running your main method) spawns 2 threads and starts them. though x.start() is written before y.start() it does not mean that thread x will run before y everytime. it can be possible that y starts running before x. it all depends upon the underlying OS. there is no guarantee given by the thread api. now coming back to your questions when you execute x.start(), lets say it runs first and it will invoke run method from 12-16. but inside there is sleep call which effectively says that make me sleep. now sleep is a static method in Thread class and SHOULD BE invoked using Thread.sleep(). but nonetheless you invoked it using y.sleep() which gets transformed to Thread.sleep() which sleeps the thread in which the call to sleep method is there. so the thread referenced by x goes to sleep. but there is another thread y which is also running while all this is happening. it will run and will print the output. but the output of 342 is not guaranteed. it can be possible that y takes time and in that time x wakes prints 2 and then 34 gets printed.