This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

thread  RSS feed

 
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: 1566
10
  • 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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!