volatile

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

文章1 文章2 文章3spa

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

# 可是阅读了这些文章以后,总想着本身写写代码验证一下code

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无输出,且一直在运行htm

# 咱们使用上volatileblog

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

    }
}
相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息