1.在修改完number值以后,while循环并没有检查到
package com.mydemo; import java.util.concurrent.TimeUnit; public class MyData { public int number=0; public void add_to_60(){ this.number=60; } } class VolatileDemo{ public static void main(String[] args) { MyData myData = new MyData(); new Thread(()->{ System.out.println(Thread.currentThread().getName() + "\t come in"); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } myData.add_to_60(); System.out.println(Thread.currentThread().getName() + "\t update number value:" + myData.number); },"AAA").start(); while (myData.number==0){} System.out.println(Thread.currentThread().getName() + "\t mission is over"+ myData.number); } }
执行结果:

2.用volatile修饰number后
package com.mydemo; import java.util.concurrent.TimeUnit; public class MyData { public volatile int number=0; public void add_to_60(){ this.number=60; } } class VolatileDemo{ public static void main(String[] args) { MyData myData = new MyData(); new Thread(()->{ System.out.println(Thread.currentThread().getName() + "\t come in"); try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); } myData.add_to_60(); System.out.println(Thread.currentThread().getName() + "\t update number value:" + myData.number); },"AAA").start(); while (myData.number==0){} System.out.println(Thread.currentThread().getName() + "\t mission is over"+ myData.number); } }
执行结果:

数值被修改后被while判断到
浙公网安备 33010602011771号