I am trying to create an example to display the difference between volatile and usual variables like:
package main;
public class TestVolatile extends Thread {
public int l = 5;
public volatile int m = -1;
public TestVolatile(String str) {
super(str);
}
public void run() {
int i = 0;
while ((l > 1) && (l < 10)) {
if (m >= 0) {
m++;
}
i++;
l = 5;
System.out.println("5=" + i + " m=" + m);
}
}
public static void main(String[] args) throws InterruptedException {
TestVolatile tva = new TestVolatile("ThreadA");
tva.start();
sleep(5);
synchronized (tva) {
tva.m = 5;
tva.l = 10;
}
}
}
So m
is volatile, l
is not. I suppose that exiting from the while loop depends on the value of l
.
Because the value of l
is not volatile - m
will be incremented at least 1 time after l
has been assigned 5. But I have run the code 10 times and always m==5.
So I suppose that I am wrong. How to fix this problem? Thank you.
Thanks for answers, but not all run well. I set like:
volatile int x = 0;
volatile int y = 0;
So now the variables have to be the same! But that is not the case.
x: 346946234 y: 346946250
x: 346946418 y: 346946422
x: 346946579 y: 346946582
x: 346946742 y: 346946745
x: 346946911 y: 346946912