I am totally puzzled with the two samples.
public class VTest {
private static /*volatile*/ boolean leap = true;
public static void main(String[] args) throws InterruptedException {
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while (leap) {
}
}
});
t2.start();
Thread.sleep(3000);
leap = false;
}
}
In this case, t2
is not able to stop, as leap
was stored locally so that t2
can't access the leap
updated in main thread.
public class VTest2 {
private static int m = 0;
public static void main(String[] args) throws InterruptedException {
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; ++i) ++m;
}
});
t2.start();
for (int i = 0; i < 10000; ++i) ++m;
Thread.sleep(3000);
System.out.println(m);
}
}
But, in this case, the m
is always be 20000
, why isn't 10000
?
Any answer will be appreciated.