java get reference to,Java AtomicReference getAndAccumulate()用法及代码示例

AtomicReference类的getAndAccumulate()方法用于原子地更新AtomicReference的当前值,并将给定的accumulatorFunction应用于当前值和给定值,并返回先前的值。 accumulatorFunction应该没有副作用,因为当尝试更新由于线程之间的争用而失败时,可能会重新应用accumulatorFunction。应用该函数时,将当前值作为其第一个参数,并将给定的update作为第二个参数。

用法:

public final E getAndAccumulate(E x,

BinaryOperator accumulatorFunction)

参数:此方法接受:

x这是更新的值,

accumulatorFunction这是两个参数的无副作用函数。

返回值:此方法返回prevoius值。

以下示例程序旨在说明getAndAccumulate()方法:

程序1:

// Java program to demonstrate

// AtomicReference.getAndAccumulate() method

import java.util.concurrent.atomic.*;

import java.util.function.BinaryOperator;

public class GFG {

public static void main(String args[])

{

// AtomicReference with value

AtomicReference ref

= new AtomicReference<>(3456);

// Value to apply getAndAccumulate

int x = 45654;

// Declaring the accumulatorFunction

// applying function to add value as string

BinaryOperator add

= (u, v) -> u.toString() + v.toString();

// apply getAndAccumulate()

int value = ref.getAndAccumulate(x, add);

// print AtomicReference

System.out.println(

"The AtomicReference previous value:"

+ value);

System.out.println(

"The AtomicReference new value:"

+ ref.get());

}

}

输出:

ea7e5022ebc8a17802f2ebdc8ad68d0c.png

程序2:

// Java program to demonstrate

// AtomicReference.getAndAccumulate() method

import java.util.concurrent.atomic.*;

import java.util.function.BinaryOperator;

public class GFG {

public static void main(String args[])

{

// AtomicReference with value

AtomicReference ref

= new AtomicReference("GFG ");

// Value to apply getAndAccumulate

String x = "Welcome";

// Declaring the accumulatorFunction

// applying function to add value as string

BinaryOperator add

= (u, v) -> v + " to " + u;

// apply getAndAccumulate()

String previousValue

= ref.getAndAccumulate(x, add);

// print AtomicReference

System.out.println(

"The AtomicReference previous value:"

+ previousValue);

}

}

输出:

720b8f3efe59e0c2ac4598339d732eda.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值