测试指令重排代码

2020-05-31  本文已影响0人  呆呆猿

加个个sleep就能禁止指令重排

package com.example.test.thread;

/**

* 指令重排测试

*/

public class Test6 {

//加volatile

static  int a =0, b =0, x =0, y =0;

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

for (int i =0; i <2000000; i++) {

a =0;

            b =0;

            x =0;

            y =0;

            /**

            * 出现的4种情况

            * 1、a =1; x= b(0) ;b=1; y=a(1)----- x=0  y=1

            * 2、b=1;y=a(0); a=1;x=b(1) ----  x=1  y =0

            * 3、a=1; b=1; x=b(1);y=a(1) ---  x=1;y=1    2个同时执行

            * 4、 x=b(0); y=a(0);a=1;b=1  ----x=0;y=0    出现指令重排

            */

            Thread thread1 =new Thread(() -> {

a =1;

                x =b;

            });

            Thread thread2 =new Thread(() -> {

b =1;

                y =a;

            });

            thread1.start();

            thread2.start();

            thread1.join();

            thread2.join();

            System.out.println("x=" +x+";y="+y);

            if (y ==0 &&x ==0) {

System.out.println("x,y都是0,i:" + i);

break;

            }

}

}

public static void setA() {

}

public void get() {

setA();

    }

}

上一篇 下一篇

猜你喜欢

热点阅读