Java中的AtomicInteger addAndGet()方法及示例
java.util.concurrent.atomic.AtomicInteger.addandget() 是java中的一个内置方法,它将函数参数中传递的值添加到之前的值中,并返回数据类型为 int 的新更新值 。
语法
public final int addAndGet(int val)
参数: 该函数接受一个强制参数 val ,指定要添加的值。
返回值: 该函数在完成添加后返回整数值。
下面的程序演示了这个函数。
程序1:
// Java Program to demonstrates
// the addandget() function
import java.util.concurrent.atomic.AtomicInteger;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicInteger val
= new AtomicInteger();
// Update the value
int c = val.addAndGet(6);
// Prints the updated value
System.out.println("Updated value: "
+ c);
}
}
输出。
Updated value: 6
程序2。
// Java Program to demonstrates
// the addandget() function
import java.util.concurrent.atomic.AtomicInteger;
public class GFG {
public static void main(String args[])
{
// Initially value as 18
AtomicInteger val
= new AtomicInteger(18);
// Prints the updated value
System.out.println("Previous value: "
+ val);
// adds the value to 18
val.addAndGet(6);
// Prints the updated value
System.out.println("Updated value: "
+ val);
}
}
输出。
Previous value: 18
Updated value: 24
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html#addAndGet-int-
极客教程