volatile是Java虚拟机提供的轻量级别的同步机制
JMM
- 可见性
- 原子性
- 有序性
计算机在执行程序是,为了提高性能,编译器和处理器常常会做指令重排,一般分为以下3中
单线程环境中确保程序最终执行结果和代码顺序执行的结果一致性
处理器在进行重新排序是必须要考虑指令之间的数据依赖性
/*
* 可见性和原子性的实例代码
* */
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class MyData {
// volatile int number = 0;
volatile int number = 0;
/*public void addNumber() {
this.number = 60;
}*/
/*public synchronized void addNumber() {
this.number = 60;
}*/
public void addself() {
this.number++;
}
// AtomicInteger atomicInteger = new AtomicInteger();
AtomicInteger atomicInteger = new AtomicInteger();
public void atomicAddSelf() {
atomicInteger.getAndIncrement();
}
}
public class DemoVolatile {
public static void main(String[] args) {
// VisibilityVerificationVolatileDemo();
AtomicityVerificationVolatileDemo();
}
private static void AtomicityVerificationVolatileDemo() {
// 原子性验证
// 定义1000个线程,调用addSelf,查看最终结果,如果结果一致则表示原子性可以保证
MyData mydata = new MyData();
for (int i = 0; i < 20; i++) {
new Thread(() -> {
// 操作数据
for (int j = 0; j < 1000; j++) {
mydata.addself();
mydata.atomicAddSelf();
}
}, String.valueOf(i)).start();
}
while (Thread.activeCount() > 2) {
Thread.yield();
}
System.out.println("number ######### " + mydata.number);
System.out.println("atomicInteger ######### " + mydata.atomicInteger);
}
private static void VisibilityVerificationVolatileDemo() {
// 验证可见性
MyData myData = new MyData();
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " start \\t");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
myData.addself();
System.out.println(Thread.currentThread().getName() + " update valus = " + myData.number);
}, "AAA").start();
while (myData.number == 0) {
}
System.out.println(Thread.currentThread().getName() + " is over ");
}
}