first:
public class VolatileTest{
public volatile int inc = 0;
public void increase(){
inc++;
}
public static void main(String[] args) {
VolatileTest test = new VolatileTest();
for(int i = 0 ; i < 2 ; i ++){
new Thread(){
public void run(){
for(int j = 0 ; j < 1000 ; j++)
test.increase();
}
}.start();
}
while(Thread.activeCount() > 1)Thread.yield();
System.out.println(test.inc);
}
}
second:
public class VolatileTest{
public volatile int inc = 0;
public void increase(){
inc++;
}
public static void main(String[] args) {
VolatileTest test = new VolatileTest();
new Thread(){
public void run(){
for(int j = 0 ; j < 1000 ; j++)
test.increase();
}
}.start();
new Thread(){
public void run(){
for(int j = 0 ; j < 1000 ; j++)
test.increase();
}
}.start();
while(Thread.activeCount() > 1)Thread.yield();
System.out.println(test.inc);
}
}
The first one uses a for and the second one doesn't, and that is the only difference, but the first one gets the result smaller than 2000, the second gets the result equals to 2000, why?