Multi-threaded risk

When using multiple threads, improper, will result in code execution is very different now imagine if you use the

Look at the following piece of code:
thread class:

class JymThread1 implements Runnable{
    private int number;

    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+":"+getNumber());
    }

    public int getNumber(){
        return number++ ;
    }
}

Test categories:

public class JymIncrementTest {
    public static void main(String[] args) {
        JymThread1 jymThread = new JymThread1();
        for(int i =0;i<10;i++){
            new Thread(jymThread).start();
        }
    }
}

Results: There are two threads to read the same data, the result is obviously problematic
Here Insert Picture Description
approach:
AtomicInteger using the read variable classes is atomic class
After modifying the code:

class JymThread1 implements Runnable{
    private AtomicInteger number = new AtomicInteger(0);

    public void run() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+":"+getNumber());
    }

    public int getNumber(){
         // 先获取,在递增
        return number.getAndIncrement();
    }
}

Test code the same
results:
Here Insert Picture Description

Lack of study time, too shallow knowledge, that's wrong, please forgive me.

There are 10 kinds of people in the world, one is to understand binary, one is do not understand binary.

Published 71 original articles · won praise 54 · views 420 000 +

Guess you like

Origin blog.csdn.net/weixin_43326401/article/details/104102867