线程冲突案例演示

我们以银行取款经典案例来演示线程冲突现象。

银行取款的基本流程可以分为如下几个步骤。

(1)用户输入账户、密码,系统判断用户的账户、密码是否匹配。

(2)用户输入取款金额。

(3)系统判断账户余额是否大于或等于取款金额。

(4)如果余额大于或等于取款金额,则取钱成功;如果余额小于取款金额,则取钱失败。

/**
 * 账户类
 */
class Account{
    //账号
    private String accountNo;
    //账户的余额
    private double balance;

    public Account(){
    }

    public Acount(String accountNo,double balance){
        this.acountNo = acountNo;
        this.balance = balance;
    }

    public String getAccountNo(){
        return accountNo;
    }

    public void setAccountNo(String accountNo){
        this.accountNo = accountNo;
    }

    public double getBalance(){
        return balance;
    }

    public void setBalance(double balance){
        this.balance = balance;
    }
}

/**
 * 取款线程
 */
class DrawThread implements Runnable {
    //账户对象
    private Account account;
    //取款金额
    private double drawMoney;
    public DrawThread(Account account,double drawMoney){
        this.account = account;
        this.drawMoney = drawMoney;
    }

    /**
     * 取款线程
     */
    @Override
    public void run(){
        //判断当前账户余额是否大于或等于取款金额
        if(this.account.getBalance() >= this.drawMoney){
            System.out.println(Thread.currentThread().getName()+" 取款成功!吐出钞票:"+this.drawMoney);
            try{
                Thread.sleep(1000);
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            //更新账户金额
            this.account.setBalance(this.account.getBalance()-this.drawMoney);
            System.out.println("\t 余额为:"+this.account.getBalance());
        }else{
            System.out.println(Thread.currentThread().getName+" 取款失败,余额不足");
        }
    }
}

public class TestDrawMoneyThread {
    public static void main(String[] args){
        Account account = new Account("1234",1000);
        new Thread(new DrawThread(account,800),"丈夫").start();
        new Thread(new DrawThread(account,800),"妻子").start();
    }
}

相关推荐

  1. 线冲突案例演示

    2024-07-11 15:32:04       24 阅读
  2. Go 线池实现案例

    2024-07-11 15:32:04       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 15:32:04       53 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 15:32:04       56 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 15:32:04       46 阅读
  4. Python语言-面向对象

    2024-07-11 15:32:04       57 阅读

热门阅读

  1. WPF-C# byte[]转ImageSource常用方法

    2024-07-11 15:32:04       23 阅读
  2. 【ubuntu22.04 安装软件报错】

    2024-07-11 15:32:04       20 阅读
  3. Redis 7.x 系列【24】哨兵模式配置项

    2024-07-11 15:32:04       15 阅读
  4. C语言9 指针

    2024-07-11 15:32:04       21 阅读
  5. 玩转HarmonyOS NEXT之配置文件篇

    2024-07-11 15:32:04       16 阅读
  6. 江苏云服务器适用于哪些场景?

    2024-07-11 15:32:04       18 阅读
  7. 【SQLite3】常用API

    2024-07-11 15:32:04       14 阅读
  8. vue3+ts实现一个表单组件

    2024-07-11 15:32:04       21 阅读
  9. LeetCode K次取反后最大化的数组和(贪心算法)

    2024-07-11 15:32:04       16 阅读
  10. 力扣3148.矩阵中的最大得分

    2024-07-11 15:32:04       18 阅读