关键字volatile的作用

本文通过一个具体例子解释了Java中volatile关键字的作用。它主要用于多线程环境中防止编译器对变量值进行预测性优化,确保线程间的可见性。当一个线程修改了一个变量的值,另一个线程可以立即看到这个变化。

很多人可能对关键字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.

转载于:https://www.cnblogs.com/RayLee/archive/2010/10/22/1858172.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值