zoukankan      html  css  js  c++  java
  • 使用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
    ", account.getBalance());
            companyThread.start();
            bankThread.start();
    
            try {
                companyThread.join();
                bankThread.join();
                System.out.printf("Account end money:%d
    ", 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

    寻找撬动地球的支点(解决问题的方案),杠杆(Java等编程语言)已经有了。xkzhangsan
  • 相关阅读:
    设计模式二(建造者、原型、桥接)
    MSSQL根据表名动态分页的存储过程以及C#.net调用使用
    查询身份证号码信息(C#.NET)
    初试三层+抽象工厂代码生成器
    NET多线程与异步编程
    【SQL.SERVER.DMVS.实战】学习笔记
    【SQL.SERVER.DMVS.实战】学习笔记(二)
    SQL Server 2005数据文件数据的存储
    ASP.NET第九天加强课程
    ASP.NET第四天加强课程
  • 原文地址:https://www.cnblogs.com/xkzhangsanx/p/10776855.html
Copyright © 2011-2022 走看看