class Mydata {
// volatile 关键字 可见性
volatile int number = 0;
public void addTo60() {
this.number = 60;
}
}
/**
* 1. 验证 volatile 可见性
* int number =0; number 变量之前根本没有添加 volatile关键字
*/
public class VolatileTest {
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(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
mydata.addTo60();
System.out.println(Thread.currentThread().getName() + "update number value: " + mydata.number);
}, "AAA").start();
while(mydata.number == 0){
}
System.out.println(Thread.currentThread().getName() + "\t mission is over, main get number value is " + mydata.number);
}
}
AAA come in
AAAupdate number value: 60
main mission is over, main get number value is 60