证明程序的指令重排序
as-if-serial虽然cpu会重排序指令,但是必须保证逻辑上是顺序的,单线程执行不能受影响
happens-before如果两条指令前后有依赖关系,是不能重排序的
1 public class AsIfSerialTest { 2 private static int x = 0, y = 0; 3 private static int a = 0, b = 0; 4 5 public static void main(String[] args) { 6 7 for(long i = 0; i < Long.MAX_VALUE; i ++) { 8 x = 0; 9 y = 0; 10 a = 0; 11 b = 0; 12 13 CountDownLatch latch = new CountDownLatch(2); 14 15 Thread t1 = new Thread(() -> { 16 // 这两条语句由于没有依赖关系,在t1线程内就可能发生指令重排序 17 a = 1; 18 x = b; 19 20 latch.countDown(); 21 }); 22 23 Thread t2 = new Thread(() -> { 24 // 这两条语句由于没有依赖关系,在t2线程内就可能发生指令重排序 25 b = 1; 26 y = a; 27 28 latch.countDown(); 29 }); 30 31 t1.start(); 32 t2.start(); 33 34 try { 35 // 为了让主线程等待这俩子线程执行完毕 36 latch.await(); 37 } catch (InterruptedException e) { 38 e.printStackTrace(); 39 } 40 41 String result = "第" + i + "次,同时出现指令重排"; 42 if(x == 0 && y == 0) { 43 System.err.println(result); 44 break; 45 } 46 } 47 } 48 }