volatile是轻量级的同步机制:
- 保证可见性
- 不保证原子性
- 禁止指令重排
JMM(Java Memory Model)Java内存模型
三大特性:
- 可见性
- 原子性
- 有序性
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class VolatileDemo {
public static void main(String[] args) {
//seeOk();
atomicTest();
}
/**
* volatile保证可见性
*/
public static void seeOk(){
Mydata my = new Mydata();
System.out.println(Thread.currentThread().getName()+"初始值:"+my.num);
new Thread(()->{
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
my.addTo60();
System.out.println(Thread.currentThread().getName()+"3秒后的值:"+my.num);
},"other thread").start();
while(my.num==0){
//等于0时不再继续往下执行
}
System.out.println(Thread.currentThread().getName()+"mission is over:"+my.num);
}
/**
* volatile不保证原子性
*/
public static void atomicTest(){
Mydata data = new Mydata();
for(int i=0;i<20;i++){
new Thread(()->{
for(int j=0;j<1000;j++){
data.addPlusPlus();
data.addAtomic();
}
}).start();
}
while(Thread.activeCount()>2){
Thread.yield();
}
System.out.println(Thread.currentThread().getName()+":int "+data.num);
System.out.println(Thread.currentThread().getName()+":AtomicInteger "+data.atomicInteger);
}
}
class Mydata{
volatile int num = 0;
AtomicInteger atomicInteger = new AtomicInteger();
public void addTo60(){
this.num = 60;
}
public void addPlusPlus(){
num++;
}
public void addAtomic(){
atomicInteger.getAndIncrement();
}
}