A
A
Alexey Chizhov2014-11-19 11:53:49
Java
Alexey Chizhov, 2014-11-19 11:53:49

Java. Threads. I do the task according to the book and the conclusion is different each time, although it should be the same. Why ?

Friends, tell a newbie.
I do the task according to the book and the output is different each time, although it should be the same 98098.98099. Why is this and what to read about it?
ed335ac66a374ab7926e2e4a2dc2208f.png

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexey Chizhov, 2014-11-21
@Alexey Chizhov

Many thanks to everyone for the replies. The problem turns out to be that incrementing (counter += add;) is not an atomic operation. I did not know that. From here and each time different and incorrect values ​​​​at the output. It goes something like this:
T1: Thread 1 reads i from memory, it is equal to 1.
T2: Thread 1 increments to 2 in its register.
T3: A context switch occurs, thread 1 is suspended, the contents of its registers are flushed to temporary storage, and the contents of the registers for thread 2 are written to the processor, and this thread starts to work.
T4: Thread 2 reads i from memory, it is equal to 1.
T5: Thread 2 increments to 2 in its register.
T6: Thread writes to memory 2.
T7: Context switch again, first thread starts running.
T8: Thread 1 is writing to memory 2.

O
one pavel, 2014-11-19
@onepavel

You have two threads using the same object. There is no synchronization between threads in actions.
Therefore, the answers will be different.
What does it mean to read? We have a habr, type "java streams" in the search, select articles according to your level and read =) In general, Schildt is good.

N
Nikolai, 2014-11-19
@j_wayne

I once read this book: www.amazon.com/Java-Concurrency-Practice-Brian-Goe...
The basics haven't changed, but concurrency has been greatly improved in Java 7.
And first, it’s probably better to read elementary things from Eckel or Schildt (but I personally don’t like Schildt’s style)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question