1.概述
java.util.concurrent.atomic.AtomicInteger。
高并发的情况下,
i++
无法保证原子性,往往会出现问题,所以引入AtomicInteger
类。
2.代码实例
2.1不使用AcomicInteger
AtomicIntegerDemo 类
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
/**
* <p> @Title AtomicIntegerDemo
* <p> @Description AtomicInteger测试
*
* @author ACGkaka
* @date 2020/4/25 10:26
*/
public class AtomicIntegerDemo {
static CountDownLatch countDownLatch = new CountDownLatch(10);
static int i = 0;
public static class AddThread implements Runnable {
@Override
public void run() {
try {
for (int j = 0; j < 10_000; j++) {
i++;
}
} finally {
countDownLatch.countDown();;
}
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Thread[] threads = new Thread[10];
for (int j = 0; j < 10; j++) {
threads[j] = new Thread(new AddThread());
}
for (int k = 0; k < 10; k++) {
threads[k].start();
}
countDownLatch.await();
System.out.println("result: " + i);
}
}
输出结果:
result: 61233
2.2使用AtomicInteger
AtomicIntegerDemo 类
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <p> @Title AtomicIntegerDemo
* <p> @Description AtomicInteger测试
*
* @author ACGkaka
* @date 2020/4/25 10:26
*/
public class AtomicIntegerDemo {
static CountDownLatch countDownLatch = new CountDownLatch(10);
static AtomicInteger i = new AtomicInteger();
public static class AddThread implements Runnable {
@Override
public void run() {
try {
for (int j = 0; j < 10_000; j++) {
i.getAndIncrement();
}
} finally {
countDownLatch.countDown();;
}
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Thread[] threads = new Thread[10];
for (int j = 0; j < 10; j++) {
threads[j] = new Thread(new AddThread());
}
for (int k = 0; k < 10; k++) {
threads[k].start();
}
countDownLatch.await();
System.out.println("result: " + i);
}
}
输出结果:
result: 100000
3.结论
不使用AtomicInteger:result: 61233
使用AtomicInteger:result: 100000
通过对比可以看到,不使用AtomicInteger的时候,由于i++
是非原子操作,i++
相当于 i=i+1
,实际上是进行了三个操作,读取i的值,加1,写入i的值,所以当多线程并发执行的时候就会出现问题,通过使用AtomicInteger().getAndIncrement()
方法可以将i++
的三个操作合并为一个原子操作,不会被线程时间片的切换而中断,从而保证了最终结果的正确性。