volatile 不能保证原子性,所以在并发的情况下,会存在自增不一致的情况。例如
有问题的代码
public class JavaDemo {
private static Integer num = 0;
public static void main(String[] args) throws InterruptedException {
CountDownLatch downLatch = new CountDownLatch(1000);
for (int i = 1; i <= 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
num++;
downLatch.countDown();
}
}).start();
}
downLatch.await();
System.out.println(num);
}
}
没问题的代码 , 使用并发包下面的方法进行自增
public class JavaDemo {
private static AtomicInteger num = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
CountDownLatch downLatch = new CountDownLatch(1000);
for (int i = 1; i <= 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
num.getAndIncrement();
downLatch.countDown();
}
}).start();
}
downLatch.await();
System.out.println(num);
}
}