所谓的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...