my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread question" Watch "Thread question" New topic
Author

Thread question

Viv Gupta
Greenhorn

Joined: Dec 01, 2005
Posts: 15
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 ?

Thanks
[ August 28, 2006: Message edited by: Viv Gupta ]
Jon Lee
Ranch Hand

Joined: Mar 04, 2005
Posts: 134
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)
Viv Gupta
Greenhorn

Joined: Dec 01, 2005
Posts: 15
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.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
By the way - the call to join() is clearly an FBO case.
The answer will be the same without it.

Yours,
Bu.

---
FBO:
Federal Bureau of Obfuscation,
Santa Clara, CA


all events occur in real time
 
 
subject: Thread question