Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Unsure about thread algorithm

 
Brandon Bay
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take from Sun e-Practice SCJP Java 5 mock exam



Which is true?

A. The output can never contain the value 10.
B. The output can never contain the value 30.
C. The output can never contain the value 297.
D. The output can never contain the value 1020.
E. The output can never contain the value 1130.





Answer : Option E is correct. With or without the yield, and with no synchronization in place, any value up to 1100 can be displayed


Are many threads "modifying the values" of the same object n? If so, how does the algorithm works? I couldn't "break" the code. How does the value 1100 come about...


Thanks for any feedback
 
Abhishek khare
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for(int x=0; x<100; x++)

This Loop runs for 100 times.

for(int x=0; x<10; x++, i++)

This loop would run only for 10 times

so the Max Value of 'i' can be 10*100 = 1000

Now if (i%10 != 0) this condition can be met only 1000/10 = 100 times

So now the Max value of 'i' can be 1000 + 100 = 1100.

Hence the answer would be E 1130 cannot be reached.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy ranchers,

Brandon asked:

Are many threads "modifying the values" of the same object n? If so, how does the algorithm works?


First question: The answer is "yes".
All thread work on the same Runnable object.
The problem is, that with unsynchronized code, you cannot determine when one thread pauses and let another thread do its job.
Therefore the answer to the second question is a bit puzzling.
First be certain that at any line of code in the run method, a thread can pause and another can run.
And all of them change values of the Runnable object they share.
E.g. thread-1 does the line with the for loop and increments the i to a number that can be divided by 10 without remainder. Then another thread starts, and sees, that i%10 == 0 and again the i will be incremented....


You see this can be very complicated.
Perhaps compile the code and run it several times. Probably you will see some differences.

Then add the keyword [i]synchronized[i] to the run-method (public synchronized void run() {... )and retry.
Big Difference!

But for training on synch the example code is a bit too complicated.
Perhaps try something easier in the first place.


Yours,
Bu.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic