Hi, all!
I've been studying concurrent programming from
Oracle Documentation. And I was
testing some code from that tutorial:
I have a class with a field that can be incremented or decremented:
And two
Thread classes for create threads: One of them for increment the Counter's value, and the other one for decrement it:
Finally, I coded a main class that creates two threads (IncrementThread and DecrementThread) with the same Counter object, and start them:
I understand when I run this little application that the printed values in console are not consistent:
Decrement thread: value = 8385
Increment thread: value = 8388
Increment thread: value = 8385
Increment thread: value = 8386
Increment thread: value = 8387
Decrement thread: value = 8384
Increment thread: value = 8388
But, what I cannot understand is that something similar happens when I synchronize the access methods to the field "value" of the Counter class (
Synchronized Methods):
With synchronized methods I get the same thing:
Decrement thread: value = 1989
Decrement thread: value = 1988
Decrement thread: value = 1987
Decrement thread: value = 1986
Increment thread: value = 1990
Decrement thread: value = 1985
Decrement thread: value = 1985
Decrement thread: value = 1984
Can someone tell me what's happening?
(Details are welcome.)
Thank you, in advance.