使用atomic类保证原子性
示例代码:
package com.hzh.atomic;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicDemo {
private static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void Cre() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
atomicInteger.incrementAndGet();
}
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
new Thread(AtomicDemo::Cre).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(atomicInteger.get());
}
}
其底层原理:
利用了乐观锁的机制思想
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021032120125740.png)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210321201503480.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQzNzEzMDQw,size_16,color_FFFFFF,t_70)
只有当前的值满足是预期值才进行更新,不然一直进行死循环,直到获取的预期值