This week's book giveaway is in the Design forum.We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!

# Unsure about thread algorithm

Brandon Bay
Greenhorn
Posts: 29
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
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
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.