指令重排序

@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"); } } } }

 

posted @ 2018-05-18 11:09  Rainyn  阅读(152)  评论(0编辑  收藏  举报