• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problem with Threads  RSS feed

 
Emilian Chmiel
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I wrote a simple program:



After run it, I get:

Thread D; Count :123; AllCash: 0
Thread B; Count :124; AllCash: 0
Thread F; Count :124; AllCash: 0
Thread C; Count :124; AllCash: 0
Thread A; Count :124; AllCash: 0

Well, when i sum up all Threads cash it should be 500...but it's not
 
Tim Moores
Saloon Keeper
Posts: 4036
94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is with concurrent access of a shared mutable resource, in this case the cash variable. Testing it and changing it (lines 11 and 12) should be one atomic operation, but in this code it's not. That means a context switch between threads can occur between lines 11 and 12, leading to inconsistencies. Try rewriting the code with cash being an object of type java.util.concurrent.atomic.AtomicInteger.
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
um up all Threads cash it should be 500...but it's not

What is the value you see that is wrong?

If the Threads are run without synchronization, its possible for a variable to be updated simultaneously  by more than one thread throwing the count off.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!