public class Test { public int state=0; public void unsafe(){ while (state<1000000000){ int a = state++; int b = state; if(a!=b-1){ System.out.println("線程不安全了,a=" + a + ",b=" + b); } } System.out.println(Thread.currentThread().getName() + "執行完畢"); } public static void main(String[] args) throws InterruptedException{ final Test mytest = new Test(); Thread th1 = new Thread("1號"){ @Override public void run() { mytest.unsafe(); } }; Thread th2 = new Thread("2號"){ @Override public void run() { mytest.unsafe(); } }; Thread th3 = new Thread("3號"){ @Override public void run() { mytest.unsafe(); } }; th1.start(); th2.start(); th3.start(); th1.join(); th2.join(); th3.join(); System.out.println("main執行完畢"); } }
輸出以下緩存
1號執行完畢
3號執行完畢
2號執行完畢
main執行完畢安全
th.join()的做用是暫停調用線程,待th線程執行完畢的時候,調用線程才能繼續執行,這裏的調用線程是main,因此mian最後執行完畢ide
我也試過在state屬性前加volatile關鍵字,可是會讓程序執行變慢不少,我想應該是volatile致使緩存失效的緣由,並且,若是隻有volatile,沒有sync,並不能達到線程安全的目的,volatile只能保證可見性,並不能保證原子性線程