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最后执行完毕
我也试过在state属性前加volatile关键字,但是会让程序执行变慢很多,我想应该是volatile导致缓存失效的原因,而且,如果只有volatile,没有sync,并不能达到线程安全的目的,volatile只能保证可见性,并不能保证原子性