Java中的并发问题案例(二)—多人同时通过一张银行卡取款
01 代码
public class SynTest1 {
public static void main(String[] args) {
Account account = new Account(10000, 12345678);
new Bank("A", account, 4000).start();
new Bank("B", account, 7000).start();
new Bank("C", account, 4000).start();
}
}
class Account {
int deposit;//存款
int number;//银行卡号
public Account(int deposit,int number){
this.deposit=deposit;
this.number=number;
}
}
class Bank extends Thread{
//存钱
//取钱
Account account;
int withdraw;//取钱
int balance;//余额
public Bank(String name,Account account,int withdraw){
super(name);//用父类构造
this.account=account;
this.withdraw=withdraw;
}
@Override
public void run() {
draw();
}
private void draw() {
//同步监视块:哪个对象要进行增删改查的操作就锁哪个对象
synchronized (account){
//判断能否取钱,账户存款小于0立即返回
if (account.deposit<=0){
System.out.println(Thread.currentThread().getName()+"取钱失败,余额为"+account.deposit);
return;
}
//为了放大问题发生性,加入延时
//判断余额是否充足
if (account.deposit-withdraw<=0){
System.out.println(Thread.currentThread().getName()+"取钱失败,余额为"+account.deposit);
return;
}
//通过延时放大问题发生性
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
balance=account.deposit-withdraw;//余额=存款-取款
account.deposit=balance;//当前存款=余额
System.out.println(Thread.currentThread().getName()+"成功取出"+withdraw+"人民币");
System.out.println("账户"+account.number+"余额为:"+balance);
}
}
}
02 运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190605222337198.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3lpbnlhbnlhbzE3NDc=,size_16,color_FFFFFF,t_70)