JMM happens-before原则个人理解

所谓的happens-before原则就是在多线程环境下,比如线程A和线程B,线程A从时间上先执行了一个action1,线程B后 执行了一个action2, 如果要求线程A执行的action1的结果对线程B执行action2的结果可见,就叫action1 happens-before action2。

这样说起来比较抽象,举个例子:

假设某个对象有一个变量x,初始值是5,线程A先调用了该对象的modifyX()方法,将x设成10,然后线程B调用该对象的getX()方法获取x的值。如果没有happens-before原则,那线程B获取到的值可能不是10,而是5。因为线程A对x的修改可能只是在cpu cache中生效,还没有写到内存中。而如果我们使用了锁机制,比如使用synchronize关键字在modifyX和getX方法上,这个时候就保证了modifyX的操作对后来的getX操作都是可见的,这就是happens-beforre原则。

一句话形容happens-before原则就是 - 时间上先发生的操作A的操作结果,对后发生的操作B是可见的。

modifyX(){

  x=10;  

}

getX(){

  return x;

}

符合happens-before原则的例子:

Program order rule. Each action in a thread happens-before every action in that thread that comes later in the program order.

Monitor lock rule. An unlock on a monitor lock happens-before every subsequent lock on that same monitor lock.

Locks and unlocks on explicit Lock objects have the same memory semantics as intrinsic locks.

Volatile variable rule. A write to a volatile field happens-before every subsequent read of that same field.

Reads and writes of atomic variables have the same memory semantics as volatile variables.

Thread start rule. A call to Thread.start on a thread happens-before every action in the started thread.

etc...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值