Kitty Creation,
I will try to explain the reasoning behind
A) 14 printing before 22 and
B) Last number printed is 12
Here we have 3 threads in play.
1. Main
Thread, Call it MT
2. Thread T2, Created in the create method, for the first time
3. Thread T22, Created in the create method, second time.
Note that create method is called twice by the main thread MT. For the first time, create is
called with integer argument 20 and second time around it is called with integer argument 10.
Now, when create is called the first time, MT creates T2 instance, prints 23, starts T2.
If for some reason main thread is taken out, (If it is blocked) T2 gets a chance to run.
Other wise Mt prints 24 and returns to call another the second create.
Now if the main thread gets blocked, T2 gets a chance to run. But since there is no reason
to pre-empt the main thread, the second create is called, which creates T22 instance, prints
13, and start T22.
Again if Main thread is not blocked, it prints 14 and returns. If it is blocked, it will not print 14.
Now depending on the scheduler either T2 or T22 gets a chance to run.
If T2 runs, 21 is printed and T2 waits on main thread (MT) to finish, MT will print 14 (if not
printed earlier), and then T2 prints 22. Then T22 runs and prints 11 and 12
If T22 runs it prints 11 and waits on T2 to finish. T2 runs and prints 21 and waits for main
thread to finish. The main thread prints 14, if not printed earlier. Then T2 prints 22.
T22 prints 12 and then finishes.
So you see always 14 is printed by the main thread(MT) before 22 is printed by the T2 and also how
T22 prints 12 at the end.
I hope I explained clear enough