This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi All, There is a question on threads from Khalid Mughal book which Iam not able to understand.
Select the two correct answers.
1. The first number printed is 13. 2. The number 14 is printed before the number 22. 3. The number 24 is printed before the number 21. 4. The last number printed is 12. 5. The number 11 is printed before the number 23
The answer is 2 and 4 . Can any one please explain the reason behind the answers ?
This is an interesting question and the answer is correct. Here is why:
* There will be three thread executed in this program: one Main and two t2.
* The following order is determined: 23, 24, 13, 14, 22, 12;
* 21 could be at any place after 23 and before 22;
* 11 could be at any place after 13 and before 12;
[ August 28, 2006: Message edited by: Jon Lee ] [ August 28, 2006: Message edited by: Jon Lee ]
SCJP 5.0 - 98% (2007)<br />SCWCD 1.4 - 97% (2007)
Joined: Dec 01, 2005
Ok let me explain this how I understand this question. 3 threads exists 1. Main 2. Thread created by the inner method call - createThread(20, Thread.currentThread()) lets call it t2-1. 3. Thread created by the outer method call - createThread(10, t2-1). call it t2-2.
t2-1 is having a join on Main thread and t2-2 has join on t2-1.
Now given such condition lets justify the answers -
1. The first number printed is 13. Not possible because System.out.println(i+3); will be the first statement to execute.
2. The number 14 is printed before the number 22. This is for sure, as 22 will be printed by thread t2-1 and 14 can only be printed by Main thread.
3. The number 24 is printed before the number 21. Can't say. Because Main and t2-1 are 2 threads that are running. Its on the scheduler which one will be executed first.
4. The last number printed is 12. This is for sure, as t2-2 will be the last to finish.
5. The number 11 is printed before the number 23 Not possible as t2-2 has a join on t2-1, and t2-1 inturn has a join on Main thread. Here 23 can only be printed by Main thread.