please anybody explain why the answer is not guaranteed to be 2000
posted 3 years ago
one.join() and two.join means let one and two finish before the main thread.
I think one and two will concurrently execute the run method and concurrently execute increase() as increase() is not synchronized.
Here is a possibility:
one: number = 0
two: number = 0
one: attempt to increase number . but number is not set to 1 in the memory yet.
two: increase number, set number = 1 in memory.
one: set number to 1 as a result of its previous step.
and so on....
I think when a number is increased by a thread, the operating system does these 3 steps in machine code:
1. put a copy of number to temporary memory
2. increase the number in this temp memory
3. copy the new value in step to and put it back to the original number's memory location.