导读:注意每一行注释
package example.volatileDemo;
/**
* @Description:
* @Date:
*/
public class VolatileVisibility {
public static class TestData {
// volatile int num = 0;//注意:这里不加volatile的话,num值不会被提交到工作内存,while将死循环
int num =0;
public void updateNum(){
num =1;
}
}
public static void main(String[] args) {
final TestData testData =new TestData();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("ChildThread num-->"+testData.num);
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
}
testData.updateNum();
System.out.println("ChildThread update num-->"+testData.num);
}
}).start();
//while 循环里面不能有synchronize、sleep等操作,否则会重新读取主存到工作内存
//println内部对当前输出内容做锁操作synchronize
while (testData.num ==0){
// System.out.println("in while loop:testData.num == 0");
// try {
// Thread.sleep(300);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// int i = 1;
}
System.out.println("MainThread num-->" + testData.num);
}
}