I have the following question: why in this case the second thread see when the first thread changes the value of number:
public static void main(String[] args) throws InterruptedException {
Temp t = new Temp();
t.go();
}
static class Temp {
int number = 2;
public void go() {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
number = 100;
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println(number);
}
}
}).start();
}
}
I expected number value to be cached from the second thread and when the first thread change it, the second thread will be "uninformed" for that and it will print always 2 ! But in practice when the first thread changed the number variable the second thread see this change and start printing 100. Why is that ? I know that it is not 100% sure that the second thread will cache the variable, but in most cases it does this. I thing that I am missing somethig important. Thanks in advance.
Shared-Memory.Tempinstance that is used to create both threads and thus both threads have access to that very same instance and its data.staticmeans that the outer class is merely a namespace, i.e. the normal "special relation" between inner and outer doesn't exist.