java指令重排序代码演示

Jdk版本:jdk1.8.0_151

代码

public class SimpleHappenBefore {

    public static void main(String[] args) throws InterruptedException {

        for(int i=0;i<500000;i++){
            SimpleHappenBefore.State state = new SimpleHappenBefore.State();
            ThreadA threadA=new ThreadA(state);
            ThreadB threadB=new ThreadB(state);
            threadA.start();
            threadB.start();

            threadA.join();
            threadB.join();
        }
    }

    static class ThreadA extends Thread{

        private final SimpleHappenBefore.State state;

        ThreadA(SimpleHappenBefore.State state) {
            this.state = state;
        }

        public void run(){
            state.a=1;
            state.b=1;
            state.c=1;
            state.d=1;
        }
    }

    static class ThreadB extends Thread{

        private final SimpleHappenBefore.State state;

        ThreadB(SimpleHappenBefore.State state) {
            this.state = state;
        }

        public void run(){
            if(state.b==1 && state.a==0){
                System.out.println("b=1");
            }

            if(state.c==1 && (state.b==0 || state.a == 0)){
                System.out.println("c=1");
            }

            if(state.d==1 && (state.a==0 || state.b==0 || state.c==0)){
                System.out.println("d==1");
            }
        }
    }

    static class State {
        public int a = 0;
        public int b = 0;
        public int c = 0;
        public int d = 0;
    }
}

输出

d==1
d==1
c=1

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0