2022-05-14 Java內存模型的Happens-Before

? Each action in a thread happens-before every subsequent action in that thread.
? An unlock on a monitor happens-before every subsequent lock on that monitor.
? A write to a volatile field happens-before every subsequent read of that volatile.
? A call to start() on a thread happens-before any actions in the started thread.
? All actions in a thread happen-before any other thread successfully returns from a join() on that thread.
? If an action a happens-before an action b,and b happens before an action c,then a happensbefore c.
? the completion of an object’s constructor happens-before the execution of its finalize method (in the formal sense of happens-before).

前三條,注意every subsequent,每個后續的。
程序順序規則:如果代碼中操作A寫在操作B之前,那么同一線程執行時,要先執行操作A,不能重排序。
監視器鎖規則:對于同一個 monitor 來說,這個 monitor 的解鎖(unlock)要 happens - before 后面對這個監視器的加鎖(lock)。
volatile變量規則:對一個 volatile 變量的寫操作 happens - before 后續任意對這個變量的讀操作。
線程啟動規則:一個對象的初始化完成(構造函數執行結束)先行發生于它的 finalize() 方法。
線程結束規則:線程中的任何操作都必須在其他線程檢測到該線程已經結束之前執行,或者從Thread.join中成功返回,或者在調用Thread.isAlive時返回false。
傳遞性:這個最好理解,不用再解釋
終結器規則:一個對象的初始化完成(構造函數執行結束)先行發生于它的 finalize() 方法。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容