多线程之转账问题

这篇博客展示了如何使用Java实现一个简单的银行账户转账示例,通过`synchronized`关键字确保线程安全。在多线程环境下,两个线程同时尝试从一个账户向另一个账户转账,代码保证了转账操作的正确性,避免了数据不一致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.Random;

/**
 * @Author: MiaoXiaoQiang
 * @Date: 2021/8/22 16:39
 * synchronized class  因为是同一个类下的多个对象都涉及资源共享的临界区问题
 */
public class ExerciseMoney {
    public static void main(String[] args) throws InterruptedException {
        Account account1 = new Account(10000);
        Account account2 = new Account(10000);
        Thread thread1 = new Thread(()->{
            for (int i = 0; i < 1000; i++) {
                account1.transfer(account2,randomAmount());
            }
        },"thread1");
        Thread thread2 = new Thread(()->{
                account2.transfer(account1,randomAmount());
        });
        thread1.start();
        thread2.start();
        thread1.join();
        thread2.join();

        System.out.println("查看两个账户的总金额:" + (account1.getMoney() + account2.getMoney()));
    }
    static Random random = new Random();
    public static int randomAmount(){
        return random.nextInt(100) + 1;
    }

}
class Account{
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
    //转账
    public void transfer(Account target, int amount){
        synchronized (Account.class) {
            if (this.money >= amount) {
                this.setMoney(this.getMoney() - amount);
                target.setMoney(target.getMoney() + amount);
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值