AtomicInteger use sample

不安全的代码

import lombok.Getter;

public class JavaNonAtomic {

    public static void main(String[] args) {
        M m = new M();
        Thread t = new Thread(m);
        Thread t2 = new Thread(m);

        t.start();
        t2.start();
        try {
            Thread.sleep(2_000*3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(m.getA());
    }


}


@Getter
class M implements  Runnable {
    int a;


    @Override
    public void run() {
        for(int i = 0; i < 1_000*10;i ++) {
            a++;
        }
    }
}

上述代码数据基本上在多线程环境下会出错。
运行效果:

image.png

使用AtomicInteger

import lombok.Getter;

import java.util.concurrent.atomic.AtomicInteger;

public class JavaAtomic {

    public static void main(String[] args) {
        M2 m = new M2();
        Thread t = new Thread(m);
        Thread t2 = new Thread(m);

        t.start();
        t2.start();
        try {
            Thread.sleep(2_000*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(m.getAi().get());
    }


}


@Getter
class M2 implements  Runnable {
    AtomicInteger ai = new AtomicInteger();


    @Override
    public void run() {
        for(int i = 0; i < 1_000*10;i ++) {
           ai.incrementAndGet();
        }
    }
}
image.png

你可能感兴趣的:(AtomicInteger use sample)