volatile 的可见性测试
A.未使用 volatile 的测试
class MyData{
int num = 0;
public void addNum(){
this.num = 60;
}
}
public class VolatileDemo {
public static void main(String[] args) {
MyData myData = new MyData();
//线程1
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "/t come in:" + myData.num);
try {
TimeUnit.SECONDS.sleep(3);
}catch (Exception e){
}
myData.addNum();
System.out.println(Thread.currentThread().getName() + "/t mission is over:" + myData.num);
},"t1").start();
//主线程操作
while(myData.num == 0){
//只有 num 刷新了,才会跳出循环
}
System.out.println(Thread.currentThread().getName() + " mission is over:" + myData.num);
}
}
总结:线程1修改 num 值之后,主线程的工作内存中的 num 没有刷新;(num 不具有内存可见性)
B.使用 volatile 的测试
class MyData{
volatile int num = 0;
public void addNum(){
this.num = 60;
}
}
public class VolatileDemo {
public static void main(String[] args) {
MyData myData = new MyData();
//线程1
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "/t come in:" + myData.num);
try {
TimeUnit.SECONDS.sleep(3);
}catch (Exception e){
}
myData.addNum();
System.out.println(Thread.currentThread().getName() + "/t mission is over:" + myData.num);
},"t1").start();
//主线程操作
while(myData.num == 0){
//只有 num 刷新了,才会跳出循环
}
System.out.println(Thread.currentThread().getName() + " mission is over:" + myData.num);
}
}
总结:线程1修改 num 值之后,主线程的工作内存中的 num 刷新了;(num 被 volatile 标记后具有了内存可见性)