I expected that when each thread executes Thread.yield (), it will pass over another thread to increase _count as follows:
In streaming applications that spin, predicting output is extremely difficult. You will need to work a lot with locks and other materials to get an excellent conclusion like A:1 B:2 C:3 ...
The problem is that everything is a race condition and unpredictable due to hardware, race conditions, randomness in time and other factors. For example, when the first thread starts, it can start for a couple of milliseconds before the next thread starts. No one will yield()
to. In addition, even if it gives, you may be on a 4-processor box, so there is no reason to stop any other threads.
Instead, I got a conclusion where A will increment the counter 100 times and then pass it to B. Sometimes all three threads will alternate sequentially, but sometimes one thread will dominate in several increments.
Correctly, in general, with these spinning cycles, you see bursts of output from a single thread when it receives temporary fragments. It also confuses the fact that System.out.println(...)
is synchronized
, which also affects time. If he did not perform a synchronized operation, you would see an even greater output.
Why does Thread.yield () always return processing to another thread?
I very rarely use Thread.yield()
. At best, this is a hint at the scheduler and is probably ignored on some architectures. The idea that it "pauses" a stream is very misleading. This may cause the thread to be returned to the end of the execution queue, but there is no guarantee that there are any threads that expect it to continue to work as if the output was deleted.
See my answer here for more info: unwanted output in multithreading