我们以银行取款经典案例来演示线程冲突现象。
银行取款的基本流程可以分为如下几个步骤。
(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;}/*** 取款线程*/@Overridepublic 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();}
}