我创建了 3 个类,
- 类 InCharge - 应检查当前余额,同时检查
Client
线程应wait()
直到InCharge
线程完成测试(15 秒) - 类客户端 - 应该每 5 秒取款,但是当
InCharge
线程运行Client
线程应该等到InCharge
线程说Notify()
- 类银行 - 持有当前余额,并锁定
Synchronized
块。
根据我的调试,它似乎是InCharge
发送Notify()
但由于某种原因客户端没有收到通知,我猜问题是因为while(true)
,但我想不出解决它的方法。
你能帮忙找出问题吗?
主要的:
public class Main {
public static void main(String[] args) {
Object obj = new Object();
Bank bank = new Bank(100000);
Client client1 = new Client(obj, bank);
InCharge inCharge = new InCharge(obj, bank);
client1.setName("client1");
inCharge.setName("inCharge");
client1.start();
inCharge.start();
}
}
银行:
public class Bank {
private int balance;
private boolean bankIsClose = false;
public Bank(int balance) {
this.balance = balance;
}
public int getBalance() {
return balance;
}
public boolean isBankIsClose() {
return bankIsClose;
}
public void setBankIsClose(boolean bankIsClose) {
this.bankIsClose = bankIsClose;
}
public void setBalance(int balance) {
this.balance = balance;
}
public synchronized void withdraw(String name, int amount){
if (this.balance - amount >= 0) {
this.balance = this.balance - amount;
System.out.println(name+" "+this.balance + " withdrawed - " + amount);
}
}
}
客户:
public class Client extends Thread {
private Object obj;
private Bank bank;
Client(Object obj, Bank bank) {
this.obj = obj;
this.bank = bank;
}
@Override
public void run() {
int randomNumber;
while (bank.getBalance() > 0) {
synchronized (obj) {
randomNumber = ((int) (Math.random() * (5000 - 1000 + 1)) + 1000);
if (!bank.isBankIsClose()) {
try {
obj.wait();
bank.withdraw(currentThread().getName(), randomNumber);
} catch (Exception e) {}
}
}
}
}
}
负责:
public class InCharge extends Thread {
private Object obj;
private Bank bank;
InCharge(Object obj, Bank bank) {
this.obj = obj;
this.bank = bank;
}
@Override
public void run() {
while (true) {
synchronized (obj) {
bank.setBankIsClose(true);
try {
System.out.println("Charge is here!, current balance is: " + bank.getBalance());
Thread.sleep(5000);
} catch (InterruptedException e) {}
bank.setBankIsClose(false);
obj.notify();
}
}
}
}