• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread

 
Sahil Manchanda
Ranch Hand
Posts: 41
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please anybody explain why the answer is not guaranteed to be 2000

 
Himai Minh
Ranch Hand
Posts: 1294
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

I am not sure if that is the case.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic