zoukankan      html  css  js  c++  java
  • volatile

    # 关于volatile的相关知识,主要阅读了一些文章

    文章1 文章2 文章3

    这几篇文章需要结合起来看,各有优点,其中文章1有一个地方有一些笔误的错别字,我当时看的时候有点迷惑,但是文章2相同的部分讲的很清楚

    # 但是阅读了这些文章之后,总想着自己写写代码验证一下

    public class QQ {
    
        private static String name = "init";
    
        private static boolean flag = false;
    
        public static void main(String[] args) throws InterruptedException {
    
            Thread thread1 = new Thread(() -> {
                System.out.println("thread1 start");
                name = "yukong";
                flag = true;
                System.out.println("thread1 end");
            });
    
            Thread thread2 = new Thread(() -> {
                while (true) {
                    if (flag) {
                        System.out.println("flag = " + flag + ", name=" + name);
                        break;
                    }
                }
            });
    
            thread2.start();
            Thread.sleep(1000);
            thread1.start();
    
        }
    
    }

      - 上面代码的执行结果是thread1执行完成,thread2无输出,且一直在运行

    # 我们使用上volatile

    public class QQ {
    
        private static String name = "init";
    
        private volatile static boolean flag = false;
    
        public static void main(String[] args) throws InterruptedException {
    
            Thread thread1 = new Thread(() -> {
                System.out.println("thread1 start");
                name = "yukong";
                flag = true;
                System.out.println("thread1 end");
            });
    
            Thread thread2 = new Thread(() -> {
                while (true) {
                    if (flag) {
                        System.out.println("flag = " + flag + ", name=" + name);
                        break;
                    }
                }
            });
    
            thread2.start();
            Thread.sleep(1000);
            thread1.start();
    
        }
    }
  • 相关阅读:
    Rust 常见集合
    Rust模块
    Rust包和crate以及模块
    Rust枚举和模式匹配
    React Native滚动到指定位置
    三行代码让你的React/RN应用动起来
    React Native添加自定义全局组件
    MAC下网易MuMu模拟器调试ReactNative
    解决React Navigation goBack()无效
    “Mac应用”已损坏,打不开解决办法
  • 原文地址:https://www.cnblogs.com/lwmp/p/11806390.html
Copyright © 2011-2022 走看看