AtomicLongFieldUpdater 细粒度处理资源

AtomicLongFieldUpdater 细粒度处理资源


注意事项

1.更新的对象属性必须使用 public volatile 修饰,数据更新后保证线程间可见
2.对象的属性修改类型原子类都是抽象类,每次使用必须使用静态方法newUpdater()创建一个更新器


示例演示

public class AccountBank {

    private Long id;
    private String bankName;
    public volatile long money;
	//使用静态方法newUpdater()创建一个更新器,设置想要更新的类的属性
    AtomicLongFieldUpdater<AccountBank> atomicLongFieldUpdater = AtomicLongFieldUpdater.newUpdater(AccountBank.class,"money");
	//提供一个线程安全的递增金额的方法
    public Long updateMoney(AccountBank accountBank){
        return atomicLongFieldUpdater.getAndIncrement(accountBank);
    }
	//省略getter  setter方法...
}

    public static void main(String[] args) throws InterruptedException {
        int size = 100;
        AccountBank accountBank = new AccountBank();
        CountDownLatch countDownLatch = new CountDownLatch(size);
        for (int i = 1; i <= size; i++) {
            new Thread(() -> {
                try {
                    for (int i1 = 0; i1 < 1000; i1++) {
                        Long aLong = accountBank.updateMoney(accountBank);
                        System.out.println("aLong = " + aLong);
                    }
                } catch (Exception e){
                    e.fillInStackTrace();
                } finally {
                    countDownLatch.countDown();
                }
            },"T_"+i).start();
        }
        countDownLatch.await();
        System.out.println("accountBank.getMoney() = " + accountBank.getMoney());
    }

演示结果

.......
aLong = 99990
aLong = 99991
aLong = 99992
aLong = 99993
aLong = 99994
aLong = 99995
aLong = 99996
aLong = 99997
aLong = 99998
aLong = 99999
accountBank.getMoney() = 100000
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值