下面是java内存模型下一些“天然”的先行发生关系,这些先行发生关系无须任何同步器协助就已经存在,可以在编码中直接使用。如果两个操作之间的关系不再此列,并且无法从下面规则中推导出来,则它们就没有顺序性保障,虚拟机可以对它们进行任意地重排序。
1.Program order rule. Each action in a thread happens-before every action in that thread that comes later in the program order.
程序次序规则:在一个线程内,按照程序代码的顺序,书写在前面的操作先行发生与书写在后面的操作。
2.Monitor lock rule. An unlock on a monitor lock happens-before every subsequent lock on that same monitor lock.
冠程锁定规则:一个锁的unlock操作先行发生于“后面”对同一个锁的lock操作。这里的“后面”是指时间上的先后顺序。
3.Volatile variable rule. A write to a volatile field happens-before every subsequent read of that same field.
volatile变量规则:对一个volatile变量的写操作先行发生于“后面”对这个变量的读操作。这里的“后面”同样是指时间上的先后顺序。
4.Thread start rule. A call to Thread.start on a thread happens-before any other thread detects taht thread has terminated, either by successfully return from Thread.join or by Thread.isAlive returning false.
线程的启动规则:Thread对象的start()方法先行发生于此线程的没一个动作。
5.Interruption rule. A thread calling interrupt on another thread happens-before the interrupted thread detects the interrupt( either by having InterruptedException thrown, or invoking isInterrupted or interrupted).
线程中断规则:对线程的interrupt()方法的调用先行发生于被中断线程的代码检测。
6.Finalizer rule. The end of a constrcutor for an object happens-before the
start of the finalizer for that obejct.
对象终结原则:一个对象的初始化完成(构造函数执行完成)先行发生与它的finalize()方法的开始。
7.Transitivity. If A happens-before B, and B happens-before C, then A
happens-before C.
传递性:你懂的。