线程解锁 m 之前对变量的写,对于接下来对 m 加锁的其它线程对该变量的读可见 t1线程对x赋值10,对于t2线程是可见的。
staticint x;static Object m =newObject();newThread(()->{synchronized(m){
x =10;}},"t1").start();newThread(()->{synchronized(m){
System.out.println(x);}},"t2").start();
线程对 volatile 变量的写,对接下来其它线程对该变量的读可见
volatilestaticint x;newThread(()->{
x =10;},"t1").start();newThread(()->{
System.out.println(x);},"t2").start();
线程 start 前对变量的写,对该线程开始后对该变量的读可见
staticint x;
x =10;newThread(()->{
System.out.println(x);},"t2").start();
happens-before 规定了对共享变量的写操作对其它线程的读操作可见,它是可见性与有序性的一套规则总结,抛开以下 happens-before 规则,JMM 并不能保证一个线程对共享变量的写,对于其它线程对该共享变量的读可见。线程解锁 m 之前对变量的写,对于接下来对 m 加锁的其它线程对该变量的读可见t1线程对x赋值10,对于t2线程是可见的。 static int x; s...