# 關於volatile的相關知識,主要閱讀了一些文章html
這幾篇文章須要結合起來看,各有優勢,其中文章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(); } }