• 原子性 与 可见性


    加锁机制既可以确保可见性又可以确保原子性,而volatile变量只能确保可见性。

    public class NoVisibility {
        private static boolean ready;
        private static int number;
        
        private static class ReaderThread extends Thread{
            public void run(){
                while(!ready){
                    Thread.yield();
                }
                System.out.println(number);
            }
        }
        
        public static void main(String[] args){
            new ReaderThread().start();
            number = 45;
            ready = true;
        }
    }

    (1)Novisibility可能会持续循环,因为ReaderThread可能会看不到写入ready的值。

    (2)NoVisibility可能会输出0,因为ReaderThread可能会看到写入ready的值,却没有看到写入number的值。--重排序(在没有同步的情况下,编译器、

    处理器、运行时都可能对操作的执行顺序进行调整)

    使用volatile的情况:

    (1)对变量的写入操作不依赖变量的当前值,或确保只有单个线程更新变量的值。

    (2)在访问变量时不需要加锁

  • 相关阅读:
    English trip -- VC(情景课)1 A Get ready
    隔板法总结
    CF 题目选做
    ZROI 提高十连测 DAY2
    2019 09 05
    线性基总结
    解决痛苦的方法/cy
    梅深不见冬 树上贪心
    ZROI 提高十连测 Day1
    [USACO09NOV]硬币的游戏 博弈 dp
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/3983406.html
Copyright © 2020-2023  润新知