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?
You need call start
to execute the code in another thread. Check this for the difference between run
and start
.
Call join
to wait the ReaderThread
finish.
volatile
keyword can build a happens-before relationship between the write and the read thread, you can put number = 50;
before ready = true;
, which makes sure the reader will notice number
is 50
when it notice ready
is true
.
Example:
Thread reader = new ReaderThread();
reader.start();
number = 50;
ready = true;
reader.join();