使用AtomicLong,经典银行账户问题

Posted xkzhangsanx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用AtomicLong,经典银行账户问题相关的知识,希望对你有一定的参考价值。

1.新建Account类,使用AtomicLong定义账户余额,增加和减少金额方法使用getAndAdd方法。

package com.xkzhangsan.atomicpack.bank;

import java.util.concurrent.atomic.AtomicLong;

public class Account {
    
    private AtomicLong balance = new AtomicLong();
    
    public void addAmount(long amount){
        this.balance.getAndAdd(amount);
    }

    public void substractAmount(long amount){
        this.balance.getAndAdd(-amount);
    }

    public long getBalance() {
        return balance.get();
    }

    public void setBalance(long balance) {
        this.balance.set(balance);
    }

}

2.Bank和Company类与https://www.cnblogs.com/xkzhangsanx/p/10759690.html一致。

3.测试类

package com.xkzhangsan.atomicpack.bank;

public class Main {
    
    public static void main(String[] args) {
        Account account = new Account();
        account.setBalance(1000);

        Company company = new Company(account);
        Thread companyThread = new Thread(company);

        Bank bank = new Bank(account);
        Thread bankThread = new Thread(bank);

        System.out.printf("Account start money:%d\\n", account.getBalance());
        companyThread.start();
        bankThread.start();

        try {
            companyThread.join();
            bankThread.join();
            System.out.printf("Account end money:%d\\n", account.getBalance());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

4.测试结果

Account start money:1000
Bank substract 1000 balance:1000
Company add 1000 balance:1000
Company add 1000 balance:1000
Bank substract 1000 balance:0
Company add 1000 balance:2000
Company add 1000 balance:2000
Company add 1000 balance:3000
Company add 1000 balance:4000
Company add 1000 balance:5000
Company add 1000 balance:6000
Company add 1000 balance:7000
Company add 1000 balance:8000
Bank substract 1000 balance:1000
Bank substract 1000 balance:7000
Bank substract 1000 balance:6000
Bank substract 1000 balance:5000
Bank substract 1000 balance:4000
Bank substract 1000 balance:3000
Bank substract 1000 balance:2000
Bank substract 1000 balance:1000
Account end money:1000

参考:java7并发编程实战手册

GitHub地址:https://github.com/xkzhangsan/java-concurrent-practice

以上是关于使用AtomicLong,经典银行账户问题的主要内容,如果未能解决你的问题,请参考以下文章

使用Semaphore同步,经典银行账户问题

如何在数据库中表示银行账户信息?

如何使用印度银行账户设置条带账户并接受国际支付?

MySQL 事务

如何使用 Stripe 向银行账户付款?

C++银行账户 项目完整代码