我正在尝试用 Java 制作一个使用多线程的程序。这个节目是关于使用借记卡的夫妻之间共享的银行账户。
我使用 2 个线程编写了 Java 程序,但我得到了java.lang.NullPointerException
我正在尝试积累我在 Java 多线程方面的知识。帮助我识别此代码块中的错误。
这是程序:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
// A bank account has a balance that can be changed by deposits and withdrawals.
public class BankAccount {
public double total = 0, amount = 0;
public void withdraw(double amount) {
total -= amount;
System.out.println("Amount Withdrawn is " + amount);
}
public void deposit(double amount) {
total += amount;
System.out.println("Amount Deposited is " + amount);
}
public double getAccount() {
System.out.println("Total Amount is " + total);
return total;
}
}
class WithdrawalRunnable {
private static final Lock lock = new ReentrantLock();
final Condition myCond = lock.newCondition();
BankAccount myAccount;
public void amountWithdrawn(double money_Withdrawn) throws InterruptedException {
lock.lock();
try {
while (money_Withdrawn > myAccount.total) {
myCond.await();
//when the condition is satisfied then :
myAccount.withdraw(money_Withdrawn);
myAccount.getAccount();
}
} finally {
lock.unlock();
}
}
}
class DepositRunnable {
private static final Lock lock = new ReentrantLock();
final Condition myCond = lock.newCondition();
BankAccount myAccount;
public void amountDeposited(double money_deposited) throws InterruptedException {
lock.lock();
try {
myAccount.deposit(money_deposited);
myAccount.getAccount();
myCond.signalAll();
} finally {
lock.unlock();
}
}
}
class Husband implements Runnable {
DepositRunnable myDeposit;
WithdrawalRunnable myWithdrawal;
double amount_deposit;
double amount_withdraw;
public Husband(double amount_deposit, double amount_withdraw) {
this.amount_deposit = amount_deposit;
this.amount_withdraw = amount_withdraw;
}
public void run() {
try {
myDeposit.amountDeposited(amount_deposit);
myWithdrawal.amountWithdrawn(amount_withdraw);
} catch (InterruptedException ex) {
Logger.getLogger(Wife.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class Wife implements Runnable {
DepositRunnable myDeposit;
WithdrawalRunnable myWithdrawal;
double amount_deposit;
double amount_withdraw;
public Wife(double amount_deposit, double amount_withdraw) {
this.amount_deposit = amount_deposit;
this.amount_withdraw = amount_withdraw;
}
public void run() {
try {
myDeposit.amountDeposited(amount_deposit);
myWithdrawal.amountWithdrawn(amount_withdraw);
} catch (InterruptedException ex) {
Logger.getLogger(Wife.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class RunningThreadTest {
public static void main(String[] args) throws InterruptedException {
Husband husb = new Husband(100.0, 0.0);
Wife wif = new Wife(400.0, 0.0);
Thread thread1 = new Thread(husb);
Thread thread2 = new Thread(wif);
thread1.start();
thread2.start();
}
}