public class OutOfOrderExecution { private static volatile int x = 0; private static volatile int y = 0; private static int a = 0, b = 0;
public static void main(String[] args) throws InterruptedException {
int i = 0; while (true) { i++; x = y = a = b = 0;
final CountDownLatch countDownLatch = new CountDownLatch(1); Thread one = new Thread(() -> { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } a = 1; x = b; });
Thread two = new Thread(() -> { try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } b = 1; y = a; }); one.start(); two.start(); countDownLatch.countDown(); one.join(); two.join();
String result = "第" + i + "次(" + "x = " + x + " y = " + y + ")"; //只有重排序的时候回出现x y 都等于0 if(x == 0 && y == 0){ System.out.println(result); break; }