1. 程式人生 > >指令重排序

指令重排序

start err exceptio ada before spa boolean class ==

@Slf4j
public class SimpleHappenBefore {

    private static int a = 0;

    private static boolean flag = false;

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 1000; i++) {
            ThreadA threadA = new ThreadA();
            ThreadB threadB 
= new ThreadB(); threadA.start(); threadB.start(); threadA.join(); threadB.join(); a = 0; flag = false; } } static class ThreadA extends Thread { @Override public void run() { //這裏的指令重排序
a
= 1; flag = true; } } static class ThreadB extends Thread { @Override public void run() { if (flag) { a = a * 1; } if (a == 0) { System.out.println("ha,a==0"); } } } }

指令重排序