关于volatile防止重排序

来源:13-5 volatile作用

qq_邪饿的小强_0

2019-12-04

关于volatile关键字防止重排序,在之前重排序的例子中,也就是OutOfOrderExecution这个类,如果我只对x,y两个变量加上volatile修饰的话,应该也可以达到代码不会出现x = 0;y = 0;的情况。因为 a = 1;一定发生在x = b之前;b = 1;一定发生在y = a;之前。不知道我的理解哪里出了问题,希望老师指正…图片描述图片描述

写回答

2回答

悟空

2019-12-04

麻烦同学贴一下完整代码

0
2
qq_邪饿的小强_0
非常感谢!
2019-12-05
共2条回复

qq_邪饿的小强_0

提问者

2019-12-05

public class OutOfOrderExecution {
   private static volatile int x = 0;
   private static volatile int y = 0;
   private static int a = 0, b = 0;

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

       int i = 0;
       while (true) {
           i++;
           x = y = a = b = 0;

           final CountDownLatch countDownLatch = new CountDownLatch(1);
           Thread one = new Thread(() -> {
               try {
                   countDownLatch.await();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               a = 1;
               x = b;
           });

           Thread two = new Thread(() -> {
               try {
                   countDownLatch.await();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               b = 1;
               y = a;
           });
           one.start();
           two.start();
           countDownLatch.countDown();
           one.join();
           two.join();

           String result = "第" + i + "次(" + "x = " + x + " y = " + y + ")";
           //只有重排序的时候回出现x y 都等于0
           if(x == 0 && y == 0){
               System.out.println(result);
               break;
           }


           //1. 1,0 2.0,1 3.1,1
           System.out.println(result);

       }
   }
}

0
2
qq_邪饿的小强_0
回复
悟空
我悟了!!感谢
2019-12-05
共2条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程