看看如下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| package com.wzl.day26;
public class VolatileVisibility { public static volatile int i = 0; public static void increase(){ i++; }
}
|
volatile的内存语义
volatile是java虚拟机提供的轻量级的同步机制。volatile关键字有如下两个作用。
可见性代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package com.wzl.day26;
public class VolatileVisibilitySample { volatile boolean initFlag = false; public void sava(){ this.initFlag = true; String threadname = Thread.currentThread().getName(); System.out.println("线程:" + threadname + ":修改共享变量initFlag"); } public void load(){ String threadname = Thread.currentThread().getName(); while (!initFlag){ } System.out.println("线程:" + threadname + "当前线程嗅探到initFlag状态的改变"); }
public static void main(String[] args) { VolatileVisibilitySample sample = new VolatileVisibilitySample(); Thread threadA = new Thread(()->{ sample.sava(); }, "threadA"); Thread threadB = new Thread(()->{ sample.load(); },"threadB"); threadB.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } threadA.start(); } }
|