static int x = 0, y = 0;static int a = 0, b = 0;void main(){ for (long i = 0; i < Long.MAX_VALUE; i++>) { x=0; y=0; a=0; b=0; CountDownLatch latch = new CountDownLatch(2); Thread one = new Thread(() -> { public void run() { a = 1; x = b; latch.countDown(); } }); Thread other = new Thread(() -> { public void run() { b = 1; y = a; latch.countDown(); } }); one.start(); other.start(); latch.await(); if (x == 0 && y == 0) { break; } }}
例子,类初始化指令换顺序
class T { int m = 8;}T t = new T();汇编码 0 new #2 <T> # 变量半初始化状态为0 3 dup 4 invokespecial #3 <T.<init>> 7 astore_1 # 4,7乱序执行, 先建立了关联再初始化, 变量中间状态值为0。线程访问时中间状态逸出 8 returnclass C { private int num = 0; public C() { new Thread(() -> System.out.println(this.num)).start(); } void main() { new C(); System.in.read(); }}