再谈volatile的可见性

volatile保证可见性的说法有问题,准确说是任何变量都可被访问,只是访问时不一定是最新的值,volatile的作用时,保证线程访问变量时拿到的永远是最新值,所以这个可见性等于保证最新值。
同时,加了Volatile的变量或者字段,在被访问时,要比不加的慢;为什么?因为Volatile底层是加了lock锁的。这就是为什么他保证了一定是最新值。



public class Testdemo {


    static class TestABC implements Runnable {
        private TestB testB;

        @Override
        public void run() {
            while (true) {
                if (testB.getData() > 0) {
                    long t = System.nanoTime();
                    t = t - TestB.time;
                    int x=1;
                }
            }

        }
    }


    static class TestB implements Runnable {

        public static long time = 0;
        public static volatile boolean start = false;

        private  int data = 0;

        @Override
        public void run() {
            while (true) {

                if (start) {
                   
                    data = 4;
                    time = System.nanoTime();
                    break;
                }
            }
        }

        public int getData() {
            return data;
        }

    }


    public static void main(String[] args) throws InterruptedException {
        TestABC testABC = new TestABC();
        TestB threadDemo = new TestB();
        testABC.testB = threadDemo;
        new Thread(threadDemo, "t1").start();
        new Thread(testABC, "t2").start();
        Thread.sleep(3000);

        TestB.start = true;
    }


}

posted @ 2022-09-05 14:34  方东信  阅读(115)  评论(0编辑  收藏  举报