aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread doubt" Watch "Thread doubt" New topic
Author

Thread doubt

sudha javvadi
Ranch Hand

Joined: Mar 23, 2007
Posts: 97
Can anybody tell me the answer and reason for the below question.It is from
http://www.sun.com/training/certification/assessment/055.jsp

22. Given:


5. class NoGo implements Runnable {
6. private int i;
7. public synchronized void run() {
8. if (i%10 != 0) { i++; }
9. for(int x=0; x<10; x++, i++)
10. { if (x == 4) Thread.yield(); }
11. System.out.print(i + " ");
12. }
13. public static void main(String [] args) {
14. NoGo n = new NoGo();
15. for(int x=0; x<101; x++) { new Thread(n).start(); }
16. }
17. }
Which is true?

The output can never contain the value 10.
The output can never contain the value 30.
The output can never contain the value 297.
The output can never contain the value 820.
The output can never contain the value 1010.

Thanks,
sudha.
dipayan chatterjee
Ranch Hand

Joined: Oct 03, 2007
Posts: 47
hello everyone i too am not able to crack this question

please help


SCJP1.4 , gearing up for SCWCD 5
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

There is a lot of obfuscation going on here.... but basically...

1. There is no real parallelism here. All 101 threads are running serially, because their run() method are synchronized with each other. (Same runnable object --> same lock)

2. Line 8 is never true. The operation starts off as zero, which means it is false. And as we shall see, it will end up as a mod 10 too, so it will be false for the next thread too. See reason 4.

3. Line 10 is useless. The yield() method doesn't release the lock, so none of the other threads waiting to run will be able to run anyway.

4. Basically, line 9 is just a fancy way of adding 10 to the variable i. (due to reason 1 and 3)

5. Line 11 is the only "output" in the program. And since it is at the end of the "add 10" operation, the output must be divisable by 10.

So the answer is the only answer on the list that is not divisable by 10, which is ... 297.


Henry
[ November 02, 2007: Message edited by: Henry Wong ]

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
dipayan chatterjee
Ranch Hand

Joined: Oct 03, 2007
Posts: 47
thanks henry for the explaination
 
jQuery in Action, 2nd edition
 
subject: Thread doubt