请大家帮我分析这段代码造成死锁的原因

ly954772930 ly954772930 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
尊敬的各位论坛的小伙伴们,对于下列代码不能解释清楚死锁的原因:
首先贴代码吧:
Account.java
public class Account {
private String acccountNo;
private double balance;
private volatile boolean flag = false;
private int i = 0;

public Account() {

}

public Account(String accountNo, double balance) {
this.acccountNo = acccountNo;
this.balance = balance;
}

public String getAcccountNo() {
return acccountNo;
}

public void setAcccountNo(String acccountNo) {
this.acccountNo = acccountNo;
}

public double getBalance() {
return this.balance;
}

public void draw(double drawAmount) {
synchronized (Account.class) {
if (!flag) {
try {
Account.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println(Thread.currentThread().getName() + "取钱:" + drawAmount);
balance -= drawAmount;
System.out.println("账户余额为:" + balance);
// 将标识账户是否有存款的旗标设为false
if (balance < 0) {
i++;
System.out.println(
"******************************************************************************************************************************************"
+ i);
flag = false;
Account.class.notifyAll();
}
}
System.out.println(flag);
}

}

public void deposit(double depositAmount) {
synchronized (Account.class) {
if (flag) {
try {
Account.class.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println(Thread.currentThread().getName() + "存款:" + depositAmount);
balance += depositAmount;
System.out.println("账户余额为:" + balance);
if (balance > 0) {
flag = true;
Account.class.notifyAll();
}
}
System.out.println(flag);
}
}
}
DepositThread.java
public class DepositThread extends Thread {
// 模拟用户账户
private Account account;
private double depositAmount;

public DepositThread(String name, Account account, double depositAmount) {
super(name);
this.account = account;
this.depositAmount = depositAmount;
}

@Override
public void run() {
for (int i = 0; i < 100; i++) {
account.deposit(depositAmount);
}
}

}
DrawThread.java
public class DrawThread extends Thread {
private Account account;
private double drawAmount;

public DrawThread(String name, Account account, double drawAmount) {
super(name);
this.account = account;
this.drawAmount = drawAmount;
}

@Override
public void run() {
for(int i=0;i<100;i++) {
account.draw(drawAmount);
}
}
}
测试代码:
DrawTest.java
public class DrawTest {
public static void main(String[] args) {
// 创建一个账户
Account acct = new Account("1234567", 0);
new DrawThread("取钱者甲", acct, 80000).start();
new DrawThread("取钱者乙", acct, 80000).start();
new DrawThread("取钱者丙", acct, 80000).start();

new DepositThread("存钱者张", acct, 80000).start();
new DepositThread("存钱者王", acct, 80000).start();
new DepositThread("存钱者刘", acct, 80000).start();
}

}
请大家帮我分析这段代码造成死锁的原因
...全文

相关推荐

评论 8
收藏 已收藏
分享
返回顶部
ly954772930
Java SE 62,621 成员 307,251 内容