package com.myspringboot.test;
import java.util.concurrent.atomic.AtomicInteger;
class MyData{
volatile Integer number = 0;
public void add(){
number++;
}
//解决Volitile的原子性问题
AtomicInteger atomicInteger = new AtomicInteger();
public void addMyAtomic(){
atomicInteger.getAndIncrement();
}
}
/*
* @Description: Volitile 可见性验证
* @Author: WDC
* @Date: 2020/3/19 12:48
**/
public class VolitileDemo {
public static void main(String[] args) {
MyData myData = new MyData();
for (int i = 0; i < 20; i++){
new Thread(()->{
for (int j = 0; j < 1000; j++){
myData.add();
myData.addMyAtomic();
}
},String.valueOf(i)).start();
}
//等待上面20个线程全部计算完成后,再用main线程取得最终结果值
//> 2 main线程和 后台gc线程
while(Thread.activeCount() > 2){
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+"\tint finally number value:"+myData.number);
System.out.println(Thread.currentThread().getName()+"\tatomic finally number value:"+myData.atomicInteger);
}
}
Volitile不保证原子性验证与AtomicInteger 代码演示
最新推荐文章于 2021-08-18 16:15:22 发布