public class TestVolatile1{ public volatile static int i=0;
public void add(){ i++; } public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { for (int i = 0; i < 10000; i++) { add(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 10000; i++) { add(); } }); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(i); } }
|
i = 10
t1
int temp = i + 1
//ThreadContextSwitch t2
t2
int tmep = i+ 1
i = 11
//write result to main memory
t1
continue execute
reread from temp
write i = 11
sync to main memory