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...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章