Distributed and high concurrency-1-concurrency question introduction

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:

Insert picture description here

3. The cause of the problem

1. Visibility
2. Atomicity

4: count++ analysis

4.1: JVM instructions

Insert picture description here

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

被切换
B
CPU
ThreadA
A线程寄存器中count=0
线程切换
A线程中count++
A线程中count=1写入内存
B线程寄存器count=0
ThreadB
B线程count++
B线程中count=1写入内存

Guess you like

Origin blog.csdn.net/qq_28500837/article/details/109648710