I want to demonstrate to my self the visibility
thread-safety problem when accessing to a variable from more than one thread without using any kind of synchronisation.
I'm running this example from Java Concurrency in Practice:
public class NoVisibility {
private static boolean ready;
private static int number;
private static class ReaderThread extends Thread {
@Override
public void run() {
while (!ready) {
Thread.yield();
}
System.out.println(number);
}
}
public static void main(String[] args) throws InterruptedException {
new ReaderThread().start();
number = 42;
ready = true;
}
}
How to make it loop forever instead of printing 42
every time I run (looping for ever means that the modification of the variable ready = true;
in the ReaderThread
thread is not visisble to the main
thread).