两个人AB通过一个账户A在柜台取钱和B在ATM机取钱-java篇

钱的数量要设置成一个静态的变量。两个人要取的同一个对象值

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: 张
 * @Date: 2019/2/11 15:00
 * @Version: 1.0
 * @Description: 1.0
 */
public class BankTest {

    public static class Account {

        private AtomicInteger amount;

        private String name;

        public void name() {
            System.out.println("账户为:" + name + "!");
        }

        public boolean deposit(String threadName, int change) {
            amount.addAndGet(change);
            if (amount.get() > 2000) {
                System.out.print("存款金额已经达到上限,存款失败");
                return false;
            }
            System.out.println("01:" + threadName + "开始存款,存款后余额为" + amount);
            return true;
        }

        public boolean withdraw(String threadName, int money) {
            if (amount.get() <= 0 || amount.get() < money) {
                System.out.println("账户金额小于0,取款失败");
                return false;
            } else {
                amount.addAndGet(-money);
                System.out.println("02:" + threadName + "开始取款,取款后余额为" + amount);
                return true;
            }
        }

        public void openAccount(String name, Integer money) {
            this.name = name;
            this.amount = new AtomicInteger(money);
            System.out.println(name + "开户成功!");
        }
    }

    public static class PersonDeposit implements Runnable {


        private Account account;

        private int deposit;

        public void deposit(Account account, int deposit) {
            this.account = account;
            this.deposit = deposit;
        }

        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            while (true) {
                if (account.amount.get() < 2000) {
                    boolean isFlag = account.deposit(threadName, deposit);
                    if (!isFlag) {
                        break;
                    }
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    break;
                }
            }
        }
    }


    public static class PersonWithdraw implements Runnable {


        private Account account;

        private int withdraw;

        public void withdraw(Account account, int withdraw) {
            this.account = account;
            this.withdraw = withdraw;
        }

        @Override
        public void run() {
            String threadName = Thread.currentThread().getName();
            while (true) {
                if (account.amount.get() > 0) {
                    boolean isFlag = account.withdraw(threadName, withdraw);
                    if (!isFlag) {
                        break;
                    }

                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                } else {

                    break;
                }
            }
        }
    }

    public static void main(String[] args) {
        Account account = new Account();
        account.openAccount("张小乙", 1000);

        PersonDeposit p1 = new PersonDeposit();
        p1.deposit(account, 50);
        Thread depositThread = new Thread(p1, "张三");

        PersonWithdraw p2 = new PersonWithdraw();
        p2.withdraw(account, 99);
        Thread withdrawThread = new Thread(p2, "李四");

        depositThread.start();
        withdrawThread.start();

    }
}

例子来源于戳戳我

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Python中的_thread模块来实现多线程,下面是一个示例程序: ```python import _thread import time balance = 1000 # 初始账户余额 def withdraw(name, amount, mode): global balance if mode == 'counter': # 在柜台 print('{}正在柜台{}元...'.format(name, amount)) time.sleep(2) # 模拟款过程 elif mode == 'atm': # 在ATM print('{}正在ATM{}元...'.format(name, amount)) time.sleep(3) # 模拟款过程 if balance >= amount: balance -= amount print('{}款{}元成功,账户余额为{}元'.format(name, amount, balance)) else: print('{}款失败,余额不足'.format(name)) # A在柜台款,B在ATM款 try: _thread.start_new_thread(withdraw, ('A', 500, 'counter')) _thread.start_new_thread(withdraw, ('B', 800, 'atm')) except: print('Error: unable to start thread') while True: pass ``` 程序中定义了一个全局变量`balance`表示账户余额,然后定义了一个`withdraw`函数用于款,其中`name`表示款人姓名,`amount`表示款金额,`mode`表示款方式(柜台ATM)。在款过程中,使用`time.sleep`模拟款的时间。如果余额充足,则更新余额并输出款成功的信息,否则输出款失败的信息。 在主程序中,使用`_thread.start_new_thread`函数创建两个线程分别表示A在柜台款和B在ATM款,并通过`while True`保持程序运行。当然,也可以使用`threading`模块来实现多线程,具体方法类似。 注意,这个程序中没有考虑并发访问账户余额的情况,如果多个线程同时对余额进行操作,可能会出现错误。为了避免这种情况,可以使用锁制来保护共享资源。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值