[英]volatile keyword can't stop loop in java
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;
}
}
After running this code, the program does not stop, which is obvious because the thread backs up variables ready into the memory of its own process. 运行此代码后,程序不会停止,这很明显,因为线程将准备好的变量备份到自己进程的内存中。 When I use volatile keyword to modify read
当我使用volatile关键字修改读取时
private volatile static boolean ready ;
the read variable will not be copied into process memory at this time. 读取的变量此时不会复制到过程存储器中。 But the program can't stop.
但是程序无法停止。 What's the reason?
什么原因? Is it related to the static keyword?
它与static关键字相关吗?
If you want the program to output 50 and return, what should you do? 如果要让程序输出50并返回,该怎么办?
You need call start
to execute the code in another thread. 您需要调用
start
才能在另一个线程中执行代码。 Check this for the difference between run
and start
. 检查一下
run
和start
之间的差异。
Call join
to wait the ReaderThread
finish. 调用
join
以等待ReaderThread
完成。
volatile
keyword can build a happens-before relationship between the write and the read thread, you can put number = 50;
volatile
关键字可以在写入线程和读取线程之间建立一个事前发生的关系,您可以将number = 50;
before ready = true;
在
ready = true;
之前ready = true;
, which makes sure the reader will notice number
is 50
when it notice ready
is true
. ,这使得确定的读者会发现
number
为50
时注意ready
是true
。
Example: 例:
Thread reader = new ReaderThread();
reader.start();
number = 50;
ready = true;
reader.join();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.