多线程之转账问题

package MultiThreadTest;

import java.math.BigDecimal;

/**
 * @author 苏雪夜酒
 * @version 1.0
 * @date 2021/10/24 22:11
 * 因为是对同一个类的不同对象 故
 * synchronized (Account.class)
 */
public class Account {
    //变量
    private BigDecimal money;
    //无参构造方法
    public Account() {
    }
    //有参构造方法
    public Account(BigDecimal money) {
        this.money = money;
    }
    //get 方法
    public BigDecimal getMoney() {
        return money;
    }
    //set 方法
    public void setMoney(BigDecimal money) {
        this.money = money;
    }
    //成员方法 转账
    public void transfer(Account targetAccount, BigDecimal amount){
        synchronized (Account.class){
            if (this.money.compareTo(amount) > 0 ){
                this.setMoney(this.getMoney().subtract(amount));
                targetAccount.setMoney(targetAccount.getMoney().add(amount));
            }
        }
    }
}
package MultiThreadTest;

import java.math.BigDecimal;
import java.util.Random;

/**
 * @author 苏雪夜酒
 * @version 1.0
 * @date 2021/10/24 22:18
 */
public class TransferMoneyThread {
    public static void main(String[] args) throws InterruptedException {
        Account account1 = new Account(new BigDecimal(10000));
        Account account2 = new Account(new BigDecimal(10000));
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                account1.transfer(account2,randomAmount());
            }
        },"thread1");
        Thread thread2 = new Thread(()->{
            for (int i = 0; i < 10; i++) {
                account1.transfer(account2,randomAmount());
            }
        },"thread2");
        //start()启动线程
        thread1.start();
        thread2.start();
        //等待一个线程结束后,另一个线程再启动
        thread1.join();
        thread2.join();
        System.out.println("account1的账户金额:" + account1.getMoney());
        System.out.println("account2的账户金额:" + account2.getMoney());
        System.out.println("两个账户的总金额:" + account1.getMoney().add(account2.getMoney()));

    }
    static Random random = new Random();
    public static BigDecimal randomAmount(){
        return new BigDecimal(random.nextDouble());
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值