Java AtomicInteger getAndAccumulate()方法及示例
Java.AtomicInteger.getAndAccumulate() 方法是一个内置的方法,它通过对当前值和作为参数传递的值应用指定的操作来更新对象的当前值。它接收一个整数作为其参数和一个IntBinaryOperator接口的对象,并将该对象中指定的操作应用于这些值。它返回之前的值。
语法
public final int getAndAccumulate(int y,
IntBinaryOperator function)
参数: 该方法接受两个参数。
- y : 一个整数,该函数将被应用。
- function:应用于对象的当前值和值y的函数。
返回值 :该函数返回当前对象的先前值。
演示该函数的例子
// Java program to demonstrate
// working of getAndAccumulate() method
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntBinaryOperator;
public class Demo {
public static void main(String[] args)
{
new UserThread("Thread A");
new UserThread("Thread B");
}
}
class Shared {
static AtomicInteger ai
= new AtomicInteger(1);
}
class UserThread implements Runnable {
String name;
UserThread(String name)
{
this.name = name;
new Thread(this).start();
}
IntBinaryOperator ibo = (x, y) -> (x * y);
int value = 5;
@Override
public void run()
{
for (int i = 0; i < 3; i++) {
int ans
= Shared.ai
.getAndAccumulate(value, ibo);
System.out.println(name + " "
+ ans);
}
}
}
输出。
Thread A 1
Thread A 5
Thread A 25
Thread B 125
Thread B 625
Thread B 3125
参考资料: https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html
极客教程