jdk中院子操作类的使用

87 阅读1分钟

概述图

image.png 在 JDK 中,原子操作类主要位于 java.util.concurrent.atomic 包中,这些类提供了一系列无锁的原子操作,以支持高效的并发编程。以下是一些常用的原子操作类及其使用示例:

1. AtomicInteger

AtomicInteger 提供了对整数的原子操作,如加法、减法等。

java
复制代码
import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample {
    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(0);
        
        // 原子加法
        int incrementedValue = atomicInteger.incrementAndGet();
        System.out.println("Incremented Value: " + incrementedValue); // 输出 1
        
        // 原子减法
        int decrementedValue = atomicInteger.decrementAndGet();
        System.out.println("Decremented Value: " + decrementedValue); // 输出 0
        
        // 原子设置值
        atomicInteger.set(100);
        System.out.println("Set Value: " + atomicInteger.get()); // 输出 100
    }
}

2. AtomicReference

AtomicReference 提供了对对象引用的原子操作。

java
复制代码
import java.util.concurrent.atomic.AtomicReference;

public class AtomicReferenceExample {
    public static void main(String[] args) {
        AtomicReference<String> atomicReference = new AtomicReference<>("Initial");

        // 原子设置新值
        atomicReference.set("Updated");
        System.out.println("Current Value: " + atomicReference.get()); // 输出 "Updated"

        // 比较并交换
        boolean result = atomicReference.compareAndSet("Updated", "New Value");
        System.out.println("Update Successful: " + result); // 输出 true
        System.out.println("Current Value: " + atomicReference.get()); // 输出 "New Value"
    }
}

3. AtomicBoolean

AtomicBoolean 提供了对布尔值的原子操作。

java
复制代码
import java.util.concurrent.atomic.AtomicBoolean;

public class AtomicBooleanExample {
    public static void main(String[] args) {
        AtomicBoolean atomicBoolean = new AtomicBoolean(false);
        
        // 原子设置值
        atomicBoolean.set(true);
        System.out.println("Current Value: " + atomicBoolean.get()); // 输出 true
        
        // 比较并交换
        boolean result = atomicBoolean.compareAndSet(true, false);
        System.out.println("Update Successful: " + result); // 输出 true
        System.out.println("Current Value: " + atomicBoolean.get()); // 输出 false
    }
}

4. AtomicLong

AtomicLong 类似于 AtomicInteger,但用于长整型。

java
复制代码
import java.util.concurrent.atomic.AtomicLong;

public class AtomicLongExample {
    public static void main(String[] args) {
        AtomicLong atomicLong = new AtomicLong(0L);
        
        // 原子加法
        atomicLong.addAndGet(5);
        System.out.println("Current Value: " + atomicLong.get()); // 输出 5
    }
}

总结

原子操作类提供了一种简单、高效的方式来处理并发编程中的共享变量,避免了使用锁带来的开销。在多线程环境中,可以通过这些类来确保数据的一致性和安全性。使用时要根据具体场景选择合适的原子类。