First, take the arguments to the createThread method:
1. The first time this method is called, the Thread argument that is passed to it is the mainthread. 2. The second time this method is called, the Thread argument that is passed is the Thread that was created in the first call.
Now, consider the thread stack:
1. The thread t2 that is created in the first call joins Thread t1 which is the mainthread. 2. The thread t2 that is created in the second call joins Thread t1, again, but this time this is the Thread created in the first call.
Let's give each thread a name. main thread, thread-first-call, thread-second-call.
Top-down is the order in which the threads are eexecuted. thread-first-call will be executed after main thread finishes. thread-second-call will be executed after thread-first-call finishes.
Each thread has its own copy of i (indicated in brackets). mainthread executes and prints the value of (i+3) and (i+4) .. i.e 23 and 24 the first time. main thread executes again and prints the value of (i+3) and (i+4) .. i.e. 13 and 14. thread-first-call executes and prints the value of (i+1) and (i+2) .. 21 and 22. Last, thread-second-call executes and prints (i+1) and (i+2) .. i.e. 11 and 12.
NOTE: 1. To understand more clearly, print the give all threads a name and print them out along with (i+n) 2. Hope you got that run() method for the Thread t2 is defined in an anonymous inner class.
Originally posted by Karthik Rajashekaran: ...do we except such type of questions in exam...
This is definitely more complex than what you should expect on the actual exam. It's good practice, because if you can work through this and understand what's going on, you're developing skills that will definitely help you on the exam. But you shouldn't need to spend this much time on a real question.