線程安全性問題-可見性
線程和線程之間,一個線程可能看不到另一個線程的操作,稱為可見性問題。
代碼:
public class Test01 { static int a = 0; public static void main(String[] args) { //匿名內(nèi)部類創(chuàng)建第一個線程 Thread t0 = new Thread(){ @Override public void run() { System.out.println("t0開始執(zhí)行了"); //循環(huán) while(true){ if(a == 10){ System.out.println("a的值是10"); break; } } } }; //匿名內(nèi)部類創(chuàng)建第二個線程 Thread t1 = new Thread(){ @Override public void run() { System.out.println("t1開始執(zhí)行了"); //讓當(dāng)前線程睡覺兩秒鐘 try { Thread.sleep(2000); } catch (InterruptedException e) { } //修改a的值 a = 10; System.out.println("t1把a的值改成10了"); } }; //開啟線程 t0.start(); t1.start(); } }
結(jié)果:
t0開始執(zhí)行了
t1開始執(zhí)行了
t1把a的值改成10了
圖解:


浙公網(wǎng)安備 33010602011771號