This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread doubt

 
sudha javvadi
Ranch Hand
Posts: 97
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello everyone i too am not able to crack this question

please help
 
Henry Wong
author
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
dipayan chatterjee
Ranch Hand
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks henry for the explaination
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic