大家都说AtomicLong是线程安全的,以下的代码预期输出500,可为什么实际执行时有时输出498、496?是不是我的理解有问题导致哪个地方写错了?
环境:windows XP sp3,jdk1.6.0_27
import java.util.concurrent.atomic.AtomicLong;
public class TestAtomicLong {
private final AtomicLong counter = new AtomicLong(0);
public AtomicLong getCounter() {
return counter;
}
public void test() {
for (int i &#61; 0; i <500; i&#43;&#43;) {
new Thread(new Runnable() {
public void run() {
counter.getAndIncrement();
}
}).start();
}
}
public static void main(String[] args) {
TestAtomicLong obj &#61; new TestAtomicLong();
obj.test();
System.out.println(obj.getCounter());//期望输出500&#xff0c;可有时输出498、496
}
}