I have write a piece of code as below to test the function of the keyword volatile. If I run this, the Thread "BBB" will never jumps out of the loop.
I can add volatile to field number of MyDate to make it visible between different thread, which can make the program finish normally. But without the volatile keyword, if I write some irrelevant statement in the While block of RunnableTwo.run(), it can also make the program run normally. So What exactly happens here?
class MyData {
int number = 0;
public void changeNumber() {
this.number = 60;
}
}
class RunnableOne implements Runnable {
private MyData myData;
public RunnableOne(MyData myData) {
this.myData = myData;
}
@Override
public void run() {
{
System.out.println("Thread" + Thread.currentThread().getName() + "init with the data:" + myData.number);
try {
Thread.sleep(200);
} catch (Exception e) {
e.printStackTrace();
}
myData.changeNumber();
System.out.println("Thread" + Thread.currentThread().getName() + "finish with the data:" + myData.number);
}
}
}
class RunnableTwo implements Runnable {
private MyData myData;
public RunnableTwo(MyData myData) {
this.myData = myData;
}
@Override
public void run() {
System.out.println("Thread" + Thread.currentThread().getName() + "init with the data:" + myData.number);
while (myData.number == 0) {
//System.out.println("wait");
}
System.out.println("Thread" + Thread.currentThread().getName() + "finish with the data:" + myData.number);
}
}
public class VolatileDemo {
public static void main(String[] args) {
MyData myData = new MyData();
new Thread(new RunnableOne(myData), "AAA").start();
new Thread(new RunnableTwo(myData), "BBB").start();
}
}