在Java中,原子操作是指不可被中断的一个或一系列操作。这些操作在执行过程中不会被其他线程干扰,从而保证了数据的一致性和线程安全。Java提供了多种原子操作的类和工具,以下是一些常见的:
java.util.concurrent.atomic 包这个包提供了一系列原子操作的类,主要包括:
AtomicInteger用于原子操作的整数。
AtomicInteger atomicInteger = new AtomicInteger(0);
int newValue = atomicInteger.incrementAndGet(); // 原子地加1并返回新值
AtomicLong用于原子操作的长整数。
AtomicLong atomicLong = new AtomicLong(0);
long newValue = atomicLong.incrementAndGet(); // 原子地加1并返回新值
AtomicBoolean用于原子操作的布尔值。
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
boolean newValue = atomicBoolean.compareAndSet(false, true); // 如果当前值为false,则设置为true并返回true
AtomicReference用于原子操作的引用类型。
AtomicReference<String> atomicReference = new AtomicReference<>("initial");
String newValue = atomicReference.compareAndSet("initial", "updated"); // 如果当前值为"initial",则设置为"updated"并返回true
AtomicIntegerFieldUpdater用于原子更新类的字段。
class MyClass {
volatile int myField;
}
AtomicIntegerFieldUpdater<MyClass> updater = AtomicIntegerFieldUpdater.newUpdater(MyClass.class, "myField");
updater.incrementAndGet(myClassInstance); // 原子地加1
AtomicLongFieldUpdater用于原子更新类的字段。
class MyClass {
volatile long myField;
}
AtomicLongFieldUpdater<MyClass> updater = AtomicLongFieldUpdater.newUpdater(MyClass.class, "myField");
updater.incrementAndGet(myClassInstance); // 原子地加1
AtomicReferenceFieldUpdater用于原子更新类的字段。
class MyClass {
volatile String myField;
}
AtomicReferenceFieldUpdater<MyClass, String> updater = AtomicReferenceFieldUpdater.newUpdater(MyClass.class, String.class, "myField");
updater.compareAndSet(myClassInstance, "initial", "updated"); // 如果当前值为"initial",则设置为"updated"并返回true
java.util.concurrent.locks 包虽然这个包主要提供的是锁机制,但也可以通过锁来实现一些原子操作。
java.util.concurrent.atomic.LongAdder 和 java.util.concurrent.atomic.DoubleAdder这些类提供了更高性能的原子累加操作,适用于高并发场景。
LongAdder longAdder = new LongAdder();
longAdder.add(1); // 原子地加1
long sum = longAdder.sum(); // 获取当前总和
java.util.concurrent.atomic.LongAccumulator 和 java.util.concurrent.atomic.DoubleAccumulator这些类提供了更灵活的原子累加操作,可以自定义累加函数。
LongAccumulator longAccumulator = new LongAccumulator((x, y) -> x + y, 0);
longAccumulator.accumulate(1); // 原子地累加1
long result = longAccumulator.get(); // 获取当前值
通过这些原子操作的类和工具,可以在多线程环境中实现高效且安全的并发控制。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。