AtomicInteger讲解
观前提示:
本文所使用的Eclipse版本为Photon Release (4.8.0)JDK版本为1.8.0_141。
1.简介
AtomicInteger保证了可见性、有序性和原子性,属于非阻塞同步,因此适用于高并发。
2.例子
使用AtomicInteger最经典的场景是自增操作(非原子性操作)。
假设开启10个线程,每个线程都对NUM进行自增操作(10次),预期想得到的最终结果为100。
2.1 非线程安全
package test;
public class Test {
private static int NUM = 0;
private static int COUNT = 10;
public static void main(String[] args) {
Thread[] t = new Thread[COUNT];
for(int i = 0; i < COUNT; i++) {
t[i] = new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < COUNT; i++) {
add();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t[i].start();
}
}
private static void add