【发布时间】:2015-12-20 03:34:11
【问题描述】:
嗯,我为使用同步的银行系统编写了一个程序。我遇到了一些错误,输出没有正确计算提款金额,并且整个输出的打印顺序不是线程的顺序……请帮助提出建议。谢谢。
帐户.java
public class Account {
private double balance = 0;
public Account(double balance) {
this.balance = balance;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
DepositThread.java
public class DepositThread implements Runnable {
private Account account;
private double amount;
public DepositThread(Account account, double amount) {
// Set the account & balance
this.account = account;
this.amount = amount;
}
public void deposit(double amount) throws InterruptedException {
double bal = account.getBalance();
if (amount <= 0) {
wait();
throw new IllegalArgumentException("Can't not deposit!");
}
bal += amount;
account.setBalance(bal);
System.out.println("Deposit " + amount + " new balance in thread number " + Thread.currentThread().getId()
+ " balance is " + bal);
}
public synchronized void run() {
// make a deposit
try {
deposit(amount);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
WithdrawThread.java
public class WithdrawThread implements Runnable {
private Account account;
private double amount;
public WithdrawThread(Account account, double amount) {
// Set the account & balance
this.account = account;
this.amount = amount;
}
public void withdraw(double amount) throws InterruptedException {
double bal = account.getBalance();
if (amount > bal) {
wait();
throw new IllegalArgumentException("Wrong amount!");
}
bal -= amount;
account.setBalance(bal);
notifyAll();
System.out.println("Withdraw " + amount + " new balance in thread number " + Thread.currentThread().getId()
+ " balance is " + bal);
}
public synchronized void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// make a withdrawal
try {
withdraw(amount);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}// end WithdrawThread class
InternetBankingSystem.java
public class InternetBankingSystem {
public static void main(String[] args) {
Account accountObject = new Account(100);
new Thread(new DepositThread(accountObject, 30)).start();
new Thread(new DepositThread(accountObject, 20)).start();
new Thread(new DepositThread(accountObject, 10)).start();
new Thread(new WithdrawThread(accountObject, 30)).start();
new Thread(new WithdrawThread(accountObject, 50)).start();
new Thread(new WithdrawThread(accountObject, 20)).start();
} // end main()
}
【问题讨论】:
-
总是根据您要检查的条件在循环中调用 wait(),如 described in the method's documentation。
标签: java synchronization runnable implements java-threads