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();
    
        }
    }
  • 相关阅读:
    logstash performance testing
    Elasticsearch ML
    jconsole远程监控logstash agent
    kafka总结
    cloudera learning8:MapReduce and Spark
    cloudera learning7:Hadoop资源管理
    cloudera learning6:Hadoop Security
    cloudera learning5:Hadoop集群高级配置
    查看硬件设备指令
    内存问题
  • 原文地址:https://www.cnblogs.com/lwmp/p/11806390.html
Copyright © 2011-2022 走看看