指令重排测试 volatile

指令重排测试

/**
 * @description: 指令重排
 * @program: lock-immortal
 * @author: Mikael
 * @date: 2021-08-03 18:55
 **/

public class Disorder {

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

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            a = 0;
            b = 0;
            x = 0;
            y = 0;

            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    a = 1;
                    x = b;  //指令重排 先执行这个代码,导致x = 0 y = 0
                }
            });

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1;
                    y = a;   //指令重排 先执行这个代码,导致x = 0 y = 0
                }
            });
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            /**
             * 我们在正常情况下 x y的值组合
             * x = 0  y = 1
             * x = 1  y = 0
             * x = 1  y = 1
             * 不可能出现 x = 0 y = 0的情况 除非发生指令重排
             */
            String result = "第" + i + "次 (" + x + "," + y + ")";
            if (x == 0 && y == 0){
                System.err.println(result);
                break;
            }else {
                System.out.println(result);
            }
        }
    }
}

指令重排测试 volatile

这是执行结果

指令重排测试 volatile

上一篇:IDEA激活码失效了怎么办


下一篇:nginx反向代理实现跨域