美文网首页
测试指令重排代码

测试指令重排代码

作者: 呆呆猿 | 来源:发表于2020-05-31 23:33 被阅读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();

        }

    }

    相关文章

      网友评论

          本文标题:测试指令重排代码

          本文链接:https://www.haomeiwen.com/subject/xwydzhtx.html