package Demo1;
/**
* 经典线程同步问题---银行取钱问题
* Created by Petty on 2017/4/10.
*/
/**
* Account类
*/
class Account{
//封装账户编号、账户余额两个成员变量
private String acccountNo;
private double balance;
public Account(){}
public Account(String accountNo,double balance){
this.acccountNo=accountNo;
this.balance=balance;
}
public void setAcccountNo(String acccountNo){
this.acccountNo = acccountNo;
}
public String getAcccountNo(){
return this.acccountNo;
}
public void setBalance(double balance){
this.balance=balance;
}
public double getBalance(){
return this.balance;
}
}
public class Thread_2 extends Thread{
//声明用户账户
private Account account;
//当前取钱线程希望取的金额
private double drawAmount;
public Thread_2(String name,Account account,double drawAmount){
super(name);
this.account=account;
this.drawAmount=drawAmount;
}
public void run() {
//使用account作为同步监视器,任何线程进入下面代码块之前,
// 必须先对account账户锁定---其他程无法获得锁,也无法修改它
synchronized (account) {
//账户金额大于取钱金额
if (account.getBalance() >= drawAmount) {
System.out.println(getName() + "取钱成功!吐出钞票" + drawAmount);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
//修改金额
account.setBalance(account.getBalance() - drawAmount);
System.out.println("账户编号:"+account.getAcccountNo()+ "的余额为" + account.getBalance());
} else {
System.out.println(getName() + "取钱失败!余额不足!");
}
}
}
public static void main(String[] args){
//创建一个账户
Account account=new Account("123456789",1000);
//创建两个线程模拟对同一个账户取钱
Thread_2 td1=new Thread_2("张三",account,800);
td1.start();
Thread_2 td2=new Thread_2("李四",account,800);
td2.start();
}
}
运行结果:
张三取钱成功!吐出钞票800.0
账户编号:123456789的余额为200.0
李四取钱失败!余额不足!