假设我有以下课程
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;
}
}