可见性问题代码
public class Single {
static boolean flag = false;
public void load() {
while (!this.flag) {
}
System.out.println("线程"+Thread.currentThread().getName()+"读到啦");
}
public void save() {
this.flag = true;
System.out.println("线程"+Thread.currentThread().getName()+"修改了flag");
}
public static void main(String[] args) {
Single single = new Single();
Thread saveThread = new Thread(() -> single.save(),"saveThread");
Thread loadThread = new Thread(() -> single.load(),"loadThread");
loadThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
saveThread.start();
}
}
线程saveThread修改了flag
一直阻塞....
使用volatile解决可见性问题
原理
当写一个volatile变量时,JMM会把该线程对应本地内存的共享变量修改的值立刻刷新到主内存中
当读一个volatile变量,JMM会把该线程工作内存的对于变量设置为无效,并且直接从主内存中读取共享变量
public class Single {
static volatile boolean flag = false;
public void load() {
while (!this.flag) {
}
System.out.println("线程"+Thread.currentThread().getName()+"读到啦");
}
public void save() {
this.flag = true;
System.out.println("线程"+Thread.currentThread().getName()+"修改了flag");
}
public static void main(String[] args) {
Single single = new Single();
Thread saveThread = new Thread(() -> single.save(),"saveThread");
Thread loadThread = new Thread(() -> single.load(),"loadThread");
loadThread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
saveThread.start();
}
}
线程saveThread修改了flag
线程loadThread读到啦