Java 中的 AtomicLong getAndIncrement()方法,带示例

原文:https://www . geesforgeks . org/atomiclong-getandincrement-method-in-Java-with-examples/

Java . util . concurrent . atomic . atomic clong . GetAnDicrement()是 Java 中的一个内置方法,它将给定值增加 1,并在更新前返回数据类型为 long 的值。

语法:

public final long getAndIncrement()

参数:函数不接受单个参数。

返回值:该函数将执行增量操作前的值返回到前一个值。

下面的程序说明了上述方法:

程序 1:

// Java program that demonstrates
// the getAndIncrement() function

import java.util.concurrent.atomic.AtomicLong;

public class GFG {
    public static void main(String args[])
    {

        // Initially value as 0
        AtomicLong val = new AtomicLong(0);

        // Decreases and gets
        // the previous value
        long res
            = val.getAndIncrement();

        System.out.println("Previous value: "
                           + res);

        // Prints the updated value
        System.out.println("Current value: "
                           + val);
    }
}

输出:

Previous value: 0
Current value: 1

程序二:

// Java program that demonstrates
// the getAndIncrement() function

import java.util.concurrent.atomic.AtomicLong;

public class GFG {
    public static void main(String args[])
    {

        // Initially value as 18
        AtomicLong val = new AtomicLong(18);

        // Increases 1 and gets
        // the previous value
        long res = val.getAndIncrement();

        System.out.println("Previous value: "
                           + res);

        // Prints the updated value
        System.out.println("Current value: "
                           + val);
    }
}

输出:

Previous value: 18
Current value: 19

参考:https://docs . Oracle . com/javase/8/docs/API/Java/util/concurrent/atomic/atomic clong . html # getAndIncrement–