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
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?
If you want the program to output 50 and return, what should you do?