public class VolatileOne {
private static boolean ready ;
private static int number ;
private static class ReaderThread extends Thread{
@Override
public void run() {
while (!ready){
Thread.yield();
}
System.out.print(number);
}
}
public static void main(String[] args) {
new ReaderThread().run();
ready = true;
number = 50;
}
}
运行这段代码后,程序并没有停止,这是显而易见的,因为线程将准备好的变量备份到自己进程的内存中。当我使用volatile关键字修改read时
private volatile static boolean ready ;
此时不会将读取的变量复制到进程内存中。但是程序不能停止。什么原因?跟static关键字有关系吗?
如果你想让程序输出50然后返回,你应该怎么做?
最佳答案
您需要调用
start
来在另一个线程中执行代码。检查thisrun
和start
的区别。调用
join
等待ReaderThread
完成。volatile
关键字可以构建一个happens-before写线程和读线程之间的关系,可以在ready = true;
之前加上number = 50;
,确保读者会注意到number
当它注意到ready
为true
时为50
。
例子:
Thread reader = new ReaderThread();
reader.start();
number = 50;
ready = true;
reader.join();
关于java - volatile 关键字无法在 Java 中停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54868694/