以银行取款经典案例来演示线程冲突现象。 银行取钱的基本流程基本上可以分为如下几个步骤。
(1)用户输入账户、密码,系统判断用户的账户、密码是否匹配。
(2)用户输入取款金额
(3)系统判断账户余额是否大于取款金额
(4)如果余额大于取款金额,则取钱成功;如果余额小于取款金额,则取钱失败。
public class DrawMoneyDemo {
public static void main(String[] args) {
Account account=new Account("1234",1000);
new DrawMoney("老公",account,800).start();
new DrawMoney("老婆",account,800).start();
}
}
/**
* 账户类
*/
class Account{
//账号
private String accountNo;
//账户余额
private double balance;
public Account(){
}
public Account(String accountNo,double balance){
this.accountNo=accountNo;
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 DrawMoney extends Thread{
//账号对象
private Account account;
//取款金额
private double drawMoney;
public DrawMoney(String name,Account account,double drawMoney){
super(name);
this.account=account;
this.drawMoney=drawMoney;
}
@Override
public void run() {
//判断当前账户余额是否大于或等于取款金额
if(this.account.getBalance()>=this.drawMoney){
System.out.println(this.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(this.getName()+"取钱失败,余额不足");
}
}
}
结果明显不对,这就是线程不同步的后果