在Java中,CAS(Compare-and-Swap)是一种无锁算法,通过JNI(Java Native Interface)调用本地方法来利用处理器提供的原子指令实现。它可以保证在多线程环境下的原子性和可见性,而无需使用传统的锁机制。以下是一个简单的Java示例,通过java.util.concurrent.atomic
包下的AtomicInteger
类来演示CAS的原理:
import java.util.concurrent.atomic.AtomicInteger;
public class CASExample {
public static AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
// 使用CAS尝试将原子整数增加1
while (true) {
// 获取当前值
int currentValue = atomicInteger.get();
// 计算新的期望值
int newValue = currentValue + 1;
// 使用compareAndSet方法尝试原子地更新值
if (atomicInteger.compareAndSet(currentValue, newValue)) {
// 更新成功,退出循环
break;
} e