導(dǎo)讀:注意每一行注釋
package example.volatileDemo;
/**
* @Description:
* @Date:
*/
public class VolatileVisibility {
public static class TestData {
//? ? ? ? volatile int num = 0;//注意:這里不加volatile的話,num值不會(huì)被提交到工作內(nèi)存验游,while將死循環(huán)
? ? ? ? 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 循環(huán)里面不能有synchronize平挑、sleep等操作安拟,否則會(huì)重新讀取主存到工作內(nèi)存
????????//println內(nèi)部對當(dāng)前輸出內(nèi)容做鎖操作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);
? ? }
}