美文网首页
2020-08-16 java中如何验证指令重排序

2020-08-16 java中如何验证指令重排序

作者: 小苏c | 来源:发表于2020-08-16 22:00 被阅读0次

    public class Test1 {

    private  static int x =0, y =0;

        private  static int a =0, b =0;

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

    int i =0;

            for (;;){

    i++;

                x =0; y =0;

                a =0; b =0;

                Thread t1 =new Thread(new Runnable() {

    public void run() {

    // 这里这个时间根据自己电脑性能调整

                        shortWait(20000);

                        a =1;

                        x =b;

                    }

    });

                Thread t2 =new Thread(new Runnable() {

    public void run() {

    b =1;

                        y =a;

                    }

    });

                t1.start();

                t2.start();

                t1.join();

                t2.join();

                String result ="第" + i +"次 (" +x +"," +y +")";

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

    System.out.println(result);

    break;

                }else {

    System.out.println(result);

                }

    }

    }

    /**

    * 等待一段时间,时间单位纳秒

        * @param interval

        */

        public static void shortWait(long interval){

    long start = System.nanoTime();

            long end;

            do{

    end = System.nanoTime();

            }while(start + interval >= end);

        }

    }

    相关文章

      网友评论

          本文标题:2020-08-16 java中如何验证指令重排序

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