1、会出现可见性问题的案例
1.1、引出可见性问题
public class VolatileDemo {
public static boolean stop=true;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
int i=0;
while (stop){
i++;
}
System.out.println("循环结束:"+i);
}).start();
Thread.sleep(1000);
stop=false;
}
}
1.2、执行结果
1.3、执行结果分析
可见循环一直未结束,没有输出:System.out.println(“循环结束:”+i);所以主线程中stop=false,对子线程 while(stop) 不可见,这就是一个可见性问题
2、利用print 进行主内存同步
2.1 代码实现
public class VolatileDemo {
public static boolean stop=true;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
int i=1;
while (stop){
i++;
System.out.println("最新数据:"+i);
}
}).start();
Thread.sleep(100);
stop=false;
}
}
2.2、执行结果
2.3 结果分析
线程正常结束了,那么print 是如何促成了可见性问题的解决呢?
print 方法主要分为两步
- IO操作:IO阻塞也会有影响,代码佐证(new File()),也会使代码正常结束
public class VolatileDemo {
//添加volatile关键字
public static boolean stop=true;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
int i=1;
while (stop){
i++;
new File("text.txt");
}
}).start();
Thread.sleep(100);
stop=false;
}
}
- synchronized:锁的释放会强制把工作内存中写的操作同步到主内存中,意味着stop=false,会把stop的值同步到主内存,while的下一次循环会读到stop=false;对这个结论进行一下佐证,下面代码执行结果也会正常结束,所以结论就是 synchronized加锁和释放锁会同步主内存
public class VolatileDemo {
public static boolean stop=true;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
int i=1;
while (stop){
i++;
synchronized (VolatileDemo.class){
}
}
}).start();
Thread.sleep(100);
stop=false;
}
}
综上所述 print即实现了syn和io操作,所以解决了可见性问题
3、Thread.sleep解决可见性问题
sleep:没有任何同步操作,会导致线程切换,线程重新竞争,系统重新分配资源,导致线程内原本的缓存失效,会重新加载主内存中新的值
public class VolatileDemo {
public static boolean stop=true;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
int i=1;
while (stop){
i++;
try {
Thread.sleep(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
Thread.sleep(100);
stop=false;
}
}
4、添加volatile关键字
4.1、代码实现
public class VolatileDemo {
//添加volatile关键字
public volatile static boolean stop=true;
public static void main(String[] args) throws InterruptedException {
new Thread(()->{
int i=1;
while (stop){
i++;
}
System.out.println("循环结束:"+i);
}).start();
Thread.sleep(100);
stop=false;
}
}
4.2、执行结果
4.3、结果分析
程序正常结束,输出了信息,说明子循环中捕获到了stop=false
5、总结
综上案例可见我们可以通过volatile关键字去解决可见性问题,这样也就不需要关心线程中是否有print或者sleep等代码操作