并发编程AtomicInteger详解
AtomicInteger 是 Java 并发包 (java.util.concurrent.atomic) 中的一个原子变量类,用于对 int 类型的变量进行原子操作。它利用底层的 CAS(Compare-And-Swap)机制,实现了无锁的线程安全。AtomicInteger 常用于需要高效、线程安全地对整数进行更新的场景。以下是 AtomicInteger 的常见使用场景和示例。
AtomicInteger 是 Java 并发编程中非常有用的工具,提供了高效的原子操作,避免了使用锁的开销和复杂性。它适用于计数器、ID 生成器、限流器、状态管理和非阻塞算法等场景。理解和正确使用 AtomicInteger,有助于编写高效且正确的并发程序。
常见使用场景
计数器
public class Counter {private AtomicInteger count = new AtomicInteger(0);public void increment() {count.incrementAndGet();}public int getCount() {return count.get();}
}
用于实现高效的线程安全计数器,避免使用传统的同步方法。
并发 ID 生成器
public class IdGenerator {private AtomicInteger id = new AtomicInteger(0);public int generateId() {return id.incrementAndGet();}
}
生成全局唯一的 ID,例如生成任务 ID、订单号等。
限流器
public class RateLimiter {private AtomicInteger currentRequests = new AtomicInteger(0);private int maxRequests;public RateLimiter(int maxRequests) {this.maxRequests = maxRequests;}public boolean tryAcquire() {if (currentRequests.incrementAndGet() <= maxRequests) {return true;} else {currentRequests.decrementAndGet();return false;}}public void release() {currentRequests.decrementAndGet();}
}
控制并发请求的数量,用于限流等场景。
状态管理:
public class Resource {private AtomicInteger state = new AtomicInteger(0);private static final int NOT_INITIALIZED = 0;private static final int INITIALIZING = 1;private static final int INITIALIZED = 2;public boolean initialize() {if (state.compareAndSet(NOT_INITIALIZED, INITIALIZING)) {// 执行初始化操作state.set(INITIALIZED);return true;}return false;}public boolean isInitialized() {return state.get() == INITIALIZED;}
}
管理共享资源的状态,例如资源的初始化状态。
非阻塞算法:
public class NonBlockingStack {private static class Node {int value;Node next;}private AtomicInteger top = new AtomicInteger(0);private Node[] stack;private AtomicInteger size = new AtomicInteger(0);public NonBlockingStack(int capacity) {stack = new Node[capacity];}public void push(int value) {Node newNode = new Node();newNode.value = value;while (true) {int currentTop = top.get();newNode.next = stack[currentTop];if (top.compareAndSet(currentTop, currentTop + 1)) {stack[currentTop] = newNode;size.incrementAndGet();return;}}}public Integer pop() {while (true) {int currentTop = top.get();if (currentTop == 0) {return null;}Node node = stack[currentTop - 1];if (top.compareAndSet(currentTop, currentTop - 1)) {size.decrementAndGet();return node.value;}}}public int getSize() {return size.get();}
}
AtomicInteger 常用于实现无锁算法,提供高效的并发控制。
示例代码
以下是一个使用 AtomicInteger 实现并发计数器的示例:
import java.util.concurrent.atomic.AtomicInteger;public class ConcurrentCounter {private AtomicInteger count = new AtomicInteger(0);public void increment() {count.incrementAndGet();}public int getCount() {return count.get();}public static void main(String[] args) throws InterruptedException {ConcurrentCounter counter = new ConcurrentCounter();Runnable task = () -> {for (int i = 0; i < 1000; i++) {counter.increment();}};Thread thread1 = new Thread(task);Thread thread2 = new Thread(task);thread1.start();thread2.start();thread1.join();thread2.join();System.out.println("Final count: " + counter.getCount());}
}
在这个示例中,AtomicInteger 确保了在多线程环境中对计数器的并发更新是线程安全的。