Java 中 happens-before 原則,是在 JSR-133 中提出的。
原文摘要:
• 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).
翻譯過來加上自己的理解就是:
- 程序次序規則:在一個線程內,按照程序代碼順序,書寫在前面的操作先行發生於書寫在后面的操作。(這里涉及到 CPU 指令重排,所以需要加入內存屏障保證有序性)
- 管程鎖定規則:對一個鎖的解鎖操作,先行發生於后續對這個鎖的加鎖操作。這里必須強調的是同一個鎖。
- volatile 變量規則:對一個 volatile 變量的寫操作先行發生於后面對這個變量的讀操作。
- 線程啟動規則:Thread 對象的 start() 方法先行發生於此線程的每一個動作。
- 線程 join() 規則:被調用 join() 方法的線程的所有操作先行發生於 join() 的返回。
- 傳遞性規則:操作 a 先發生於操作 b,操作 b 先發生於操作 c,則操作 a 先發生於操作 c。
- 對象終結規則:一個對象的初始化完成(構造函數執行結束)先行發生於它的 finalize() 方法。
- Java 自學指南
- Java 面試題匯總PC端瀏覽【點這里】
- Java知識圖譜
- Java 面試題匯總小程序瀏覽,掃二維碼
所有資源資源匯總於公眾號