代码改变世界

关键字volatile的作用

2010-10-22 12:00  RayLee  阅读(439)  评论(0编辑  收藏  举报

很多人可能对关键字volatile的作用不太清楚。首先,该关键字是用在多线程环境中的,今天从别人的文章中找到了一个例子说明,以帮助理解。

The volatile keyword was introduced to the language as a way around optimizing compilers. Take the following code for example:

class VolatileTest {

   boolean flag;
   public void foo() {
      flag = false;
      if(flag) {
         //this could happen
      }
   }
}

An optimizing compiler might decide that the body of the if statement would never execute, and not even compile the code. If this class were accessed by multiple threads, flag could be set by another thread after it has been set in the previous code, but before it is tested in the if statement. Declaring variables with the volatile keyword tells the compiler not to optimize out sections of code by predicting the value of the variable at compile time.