1. Code analysis:
public class SynTest {
private static int count=0;
public static void addCount(){
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
public static void main(String[] args) throws InterruptedException{
for(int i=0;i<1000;i++){
new Thread(()->SynTest.addCount()).start();
}
Thread.sleep(3000);
System.out.println("count:"+count);
}
}
2. Execution result:
3. The cause of the problem
1. Visibility
2. Atomicity
4: count++ analysis
4.1: JVM instructions
4.2: Analysis
If you strictly follow the order of 14=>19 (atomicity), there will be no problem, so where does the problem occur? That is the CPU rotation training. The CPU running steps for thread switching are as follows:
1> Thread switching occurs when thread A runs to count=0, CPU runs thread B, thread B finishes all steps, and count=1;
2>CPU switches back A thread, the count in the A thread register is still 0, continue to execute the A thread code, after the A thread ends, count=1;
3> After the two threads end, the count is 1, not the expected 2