Volatile可见性测试


package com.test;

/**
 * Volatile 可见性测试
 */
public class VolatileDemo {

    public static void main(String[] args) {
        MyData myData = new MyData();

        new Thread(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            myData.addTo60();

            System.out.println(Thread.currentThread().getName() + "; " + myData.num);
        }).start();

        while (myData.num == 0) {

        }

        System.out.println(Thread.currentThread().getName() + "; " + myData.num);
    }

}

class MyData {

    volatile int num = 0;

    public void addTo60() {
        this.num = 60;
    }

}