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();

    }
}
原文地址:https://www.cnblogs.com/lwmp/p/11806390.html