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只能保证可见性,并不能保证原子性线程