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.