Re: Working with threads. Example from java docs
Progzmaster wrote:
One more time thank you for your help ,
I can't understand why it didn't happen in first version, increments
aren't atomic operations after all.
The CPU time scheduler is really a big question mark :) You can never
preddict the operation sequence
Correct. However, a lot of scheduler behavior can be explained by
remembering a few basic principles:
1. Context switches waste time, so the scheduler tries to do them as
infrequently as possible subject to the other objectives. It's a bit
like being in the middle of some paperwork, with all the right papers
spread out on your desk, and having to switch to a different job that
needs different papers.
2. On the other hand, the scheduler tries to be fair in the long term
among jobs of similar priority.
3. Thread.yield() requires a pause in the current thread to allow other
threads to run, even if the dispatcher is not yet ready to take the
processor away from it.
Now look at the original program in terms of these ideas. The yield
calls cause switches between the two threads. The time from one yield to
the next is so short that the dispatcher is very unlikely to switch
between the two threads except at the yields.
I was able to get some inconsistent outputs from your original program
by running it on a dual processor system, where both threads can really
run at the same time, rather than time sharing a single processor.
Patricia