允许针对天真的循环器进行Java内存模型优化

时间:2018-10-15 16:43:07

标签: java java-memory-model memory-model

假设我有以下课程

Looper.java

class Looper {
  boolean stop;

  void loop() {
    while(!stop) {
      // do something
    }
  }

  void stop() {
    stop = true;
  }
}

Launcher.java

class Launcher {
  public static void main(String[] args) {
    Looper looper = new Looper();
    new Thread(() -> looper.loop()).start();
    new Thread(() -> looper.stop()).start();
  }
}

编译器/ JIT / CPU将Looper类转换为以下方式以使循环永不终止是否合法?

class Looper {
  boolean stop;

  void loop() {
    while(true) { // as stop is always false from the the thread that enters this method
      // do something
    }
  }

  void stop() {
    stop = true;
  }
}

0 个答案:

没有答案