为了防止程序重排序,慎用volatile

之前在InfoQ看到一篇关于java重排序的一篇文章,觉得里面有些知识写得太绝对了,于是想通过实际程序来说明一下:

关于java重排序,这里就不做介绍了,我们知道JVM底层封装了与OS的交互,它内部有自己的一套类似于OS的内存模型,程序重排序的设计思路基本上是来源于OS。下面直接入正题吧!

我们知道JVM给每个线程分配了自己的内存空间,也就是说在变量存储方面,分为主内存和线程工作内存,也就是说,所有线程共享主内存,每个线程都有自己的工作内存。程序执行的时候是去工作内存里面取值还是去主内存里面取值呢?下面以代码为例:

publicclassDemoWork{privatebooleanstop=false;privatebooleanstart=true;publicvoidworkThread()throwsInterruptedException{ThreadworkThread=newThread(newRunnable(){privateinti=0;@Overridepublicvoidrun(){//TODOAuto-generatedmethodstubwhile(!stop){i++;/*try{Thread.sleep(10);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}*/}start=false;}});workThread.start();Thread.sleep(1000);stop=true;ThreadprintThread=newThread(newRunnable(){privateinti=0;@Overridepublicvoidrun(){//TODOAuto-generatedmethodstubwhile(stop&&start){System.out.println(“stopis:”+stop);try{Thread.sleep(10);}catch(InterruptedExceptione){//TODOAuto-generatedcatchblocke.printStackTrace();}}}});printThread.start();}/***@paramargs*@throwsInterruptedException*/publicstaticvoidmain(String[]args)throwsInterruptedException{//TODOAuto-generatedmethodstubDemoWorkdw=newDemoWork();dw.workThread();}}

上面的代码是不会停下来的,但是如果把sleep那段代码的注释去掉程序就能停下来了,这是什么原因呢?我的理解是:因为线程printThread是能正常执行的,所以有两种可能:

积极思考造成积极人生,消极思考造成消极人生。

为了防止程序重排序,慎用volatile

相关文章:

你感兴趣的文章:

标签云: