import java.util.concurrent.atomic.AtomicInteger;
public class Atomicity {
private static volatile int nonAtomicCounter = 0;
private static long nonVolNonAtomicCountter = 0;
private static volatile AtomicInteger atomicCounter = new AtomicInteger(0);
private static int times = 0;
//对单个的普通 变量的写用同一个监视器同步
public static synchronized void set(long l) {
nonVolNonAtomicCountter = l;
}
//对单个的普通变量的读用同一个监视器同步
public static synchronized long get() {
return nonVolNonAtomicCountter;
}
public static void getAndIncrement () { //普通方法调用
long temp = get(); //调用已同步的读方法
temp += 1L; //普通写操作
set(temp); //调用已同步的写方法
}
public static void caculate() {
times++;
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Ove
volatile、非volatile、Atomic计数器比较
最新推荐文章于 2024-04-22 11:31:09 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)