📅  最后修改于: 2023-12-03 15:01:50.667000             🧑  作者: Mango
AtomicInteger intValue()
方法及示例在Java中,AtomicInteger
是一个提供了原子操作的整型变量。它可以用来在多个线程中进行安全的原子操作,避免了由于多线程竞争而导致的数据不一致性问题。
intValue()
方法是AtomicInteger
类的一个成员方法,用于获取当前AtomicInteger
对象的值并返回一个普通的整型值。
下面是AtomicInteger intValue()
方法的语法:
public int intValue()
下面是一个使用AtomicInteger intValue()
方法的示例代码:
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerExample {
private static AtomicInteger counter = new AtomicInteger(0);
public static void main(String[] args) {
// 获取当前AtomicInteger对象的值并打印
System.out.println("初始值:" + counter.intValue());
// 使用incrementAndGet()方法对值进行增加,并获取增加后的值
int nextValue = counter.incrementAndGet();
System.out.println("增加后的值:" + nextValue);
// 使用addAndGet()方法对值进行增加,并获取增加后的值
nextValue = counter.addAndGet(5);
System.out.println("增加后的值:" + nextValue);
// 获取当前AtomicInteger对象的值并打印
System.out.println("最终值:" + counter.intValue());
}
}
上述代码中,我们首先创建了一个AtomicInteger
对象counter
,并初始化为0。然后使用intValue()
方法获取初始值并打印。接着,使用incrementAndGet()
方法对值进行增加,并使用intValue()
方法获取增加后的值并打印。然后,使用addAndGet()
方法对值进行增加,并使用intValue()
方法获取增加后的值并打印。最后,再次使用intValue()
方法获取最终的值并打印。
运行以上代码,会产生如下输出:
初始值:0
增加后的值:1
增加后的值:6
最终值:6
该示例展示了如何使用AtomicInteger
的intValue()
方法获取其当前值,并进行一些常见的原子操作。
你可以根据需要修改示例代码,进一步探索AtomicInteger
类的其他方法和使用方式。
注意: AtomicInteger intValue()
方法是线程安全的。