面试题
https://blog.csdn.net/luckywuxn/article/details/132712571
使用例子
public class VolatileTest {
private volatile int num = 1;
@Test
public void testUsage() {
MyDate myDate = new MyDate(); //资源类,线程操作资源类
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "\t come in");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
myDate.addTo60();
System.out.println(Thread.currentThread().getName() + "\t Update number value " + myDate.number);
}, "AAA").start();
while (myDate.number == 0) {
} //main线程一直循环,直至number不为空
System.out.println(Thread.currentThread().getName() + "\t mission is over" + myDate.number);
try {
Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
class MyDate {
volatile int number = 0;
// int number = 0;
public void addTo60() {
this.number = 60;
}
}
可以通过注释MyDate类里面的number 的定义行, 观察打印的日志, 如果使用volatile定义, 打印出来的是
AAA come in
AAA Update number value 60
Test worker mission is over60
如果没有volatile的定义就只打印这两行
AAA come in
AAA Update number value 60
也就是在其他线程永远观察不到myDate.number的值的更改