一個例子讓你明白volatile關鍵字的作用
阿新 • • 發佈:2018-12-22
作為一個菜鳥,我學習volatile都只能瞭解個大概,都是給我一堆花裡胡哨的廢話,舉例沒一個是有用的,因此我總覺得volatile關鍵件沒啥卵用,為啥,看看別人給的例子
這裡有volatile和沒volatile有區別嗎?我是覺得沒區別的,今天不想再當糊塗鬼了,找了根據它的作用,我終於弄出一個證明他有用的例子了,作用不說,自己動手跑一下就知道作用了:如果這都還不明白那就沒辦法了
public class VolatileUnsafe { private static class VolatileVar implements Runnable{ public static Object o = new Object(); private volatile Boolean flag = true; //有volatile和沒volatile效果明顯 @Override public void run() { while (true) { if (flag) { System.out.println(Thread.currentThread().getName()+":>>>>>"+flag); } } } } public static void main(String[] args) throws InterruptedException { VolatileVar v = new VolatileVar(); Thread t1 = new Thread(v); Thread t2 = new Thread(v); Thread t3 = new Thread(v); Thread t4 = new Thread(v); t1.start(); t2.start(); t3.start(); t4.start(); Thread.sleep(500); v.flag=false; System.out.println("I sleep 3s"); Thread.sleep(3000); System.out.println("I will start now"); v.flag=true; } }